In: Computer Science
Please look at the following code. When I run it from the command line, I am supposed to get the following results:
1: I am
1: I am
I need to fix it so that the functions 'print_i' and 'print_j' print all of their lines. What do I need to add? Thank you.
C source code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
// These two functions will run concurrently
void* print_i(void *ptr)
{
printf("1: I am \n");
sleep(1);
printf("in i\n");
}
void* print_j(void *ptr)
{
printf("2: I am \n");
sleep(1);
printf("in j\n");
}
int main() {
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);
int rc2 = pthread_create(&t2, NULL, print_j, NULL);
exit(0);
}
Step(1)
First Of all You Try To implement A thread Concept ,let me elaborate Thread First then I give Solution For your Code As well.
A thread of execution is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments, while sharing a same address space.
An initialized thread object represents an active thread of
execution; Such a thread object is joinable, and has a
unique thread id.
A default-constructed (non-initialized) thread object is not
joinable, and its thread id is common for all
non-joinable threads.
Step(2)
I Try to write a code in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
// These two functions will run concurrently
void* print_i(void *threadid)
{
printf("1: I am \n");
sleep(1);
printf("in i\n");
}
void* print_j(void *threadid)
{
printf("2: I am \n");
sleep(1);
printf("in j\n");
}
int main()
{
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, (void *)1);
int rc2 = pthread_create(&t2, NULL, print_j, (void *)2);
// Wait for the threads to finish
pthread_join(t1, NULL);
pthread_join(t2, NULL);
exit(0);
}
Output
1: I am
1: I am
in i
in i
Step(3)
SceenShot Of Program
Output
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------