编写简单的C代码,尝试控制来自两个不同线程的输出:
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
sem_t sem;
void* thread_func(void* aArgs)
{
printf("Entering thread %p with %d\n", (void*)pthread_self(), (int)aArgs);
int i = 0;
for(;i < 10; i++)
{
sem_wait(&sem);
if ((i % 2) == (int)aArgs)
printf("val is %d in thread %p \n", i, (void*)pthread_self());
sem_post(&sem);
}
}
int main()
{
pthread_t thread_1, thread_2;
sem_init(&sem, 0, 1);
pthread_create(&thread_1, NULL, (void*)thread_func, (void*)0);
pthread_create(&thread_2, NULL, (void*)thread_func, (void*)1);
pthread_join(thread_1, NULL);
pthread_join(thread_2, NULL);
sem_destroy(&sem);
return 0;
}
我想要实现的是交替排列的奇数和偶数。但是,我却从一个线程中得到了所有数字,然后从另一个线程中得到了所有其他数字,就像这样(即使我增加循环计数器的数量):
Entering thread 0xb75f2b40 with 0
val is 0 in thread 0xb75f2b40
val is 2 in thread 0xb75f2b40
val is 4 in thread 0xb75f2b40
val is 6 in thread 0xb75f2b40
val is 8 in thread 0xb75f2b40
Entering thread 0xb6df1b40 with 1
val is 1 in thread 0xb6df1b40
val is 3 in thread 0xb6df1b40
val is 5 in thread 0xb6df1b40
val is 7 in thread 0xb6df1b40
val is 9 in thread 0xb6df1b40
问题是为什么两个独立的线程表现得像它们是两个顺序任务?为什么第二个线程没有控制执行,直到第一个线程完成所有工作?
我尝试在for循环的末尾添加pthread_yield(),但情况并没有显著改变:有时我得到期望的输出,有时就像上面描述的那样。
更新。如何实现确定性的逐一线程执行?是否有任何同步原语可以实现这一点?