When I complie this code I can get a result like this enter image description here
The code is like this
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <sched.h>
void *thread_entry(void *ptr)
{
int i, j, len;
char *str = (char *) ptr;
len = strlen(str);
for (i = 0; i < 10; i++)
{
for (j = 0; j < len; j++) {
putchar(str[j]);
sched_yield(); /*to yield CPU*/
}
putchar('\n');
}
}
int main()
{
pthread_t thread1, thread2;
const char *msg1 = "Hello This is Thread 1.";
const char *msg2 = "I am Thread 2.";
pthread_create(&thread1, NULL, thread_entry, (void *) msg1);
pthread_create(&thread2, NULL, thread_entry, (void *) msg2);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
That is code. I think because of Common Resource but I am not sure. Please teach me why the result is like this. I really appereciate it!
It is absolutely as you think. The output is a shared resource and the two threads are simultaneously trying to push characters to it. Indeed you've put a yield in that will encourage (but not control) flipping in and out of the threads.
You've done nothing to control the interleaving of the two threads and you inevitably get the garbled output shown in the screen shot.
Without knowing what you're trying to do there isn't a lot more to say.