【发布时间】:2017-04-04 07:25:21
【问题描述】:
当我编译这段代码时,我可以得到这样的结果 enter image description here
代码是这样的
#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;
}
那是代码。我认为是因为 Common Resource,但我不确定。请教我为什么结果是这样的。我真的很欣赏它!
【问题讨论】:
-
你已经说过了。这里有比赛条件。您应该在临界区周围使用
pthread_mutex_lock()和pthread_mutex_unlock()。 -
@John Is No 谢谢你这么说!!
-
这段代码是特意设计来突出显示多个线程对输出流的使用。这显然是一项学术活动。请咨询您的教授/导师以获取更多指导。
标签: ubuntu operating-system mutual-exclusion