【发布时间】:2016-05-28 12:43:35
【问题描述】:
我想同步线程以打印 1 到 20,其中线程 1 打印奇数,线程 2 打印偶数
我用两个信号量实现了这一点。
问题:
1) 是否可以仅使用一个信号量来实现?
2) 有没有有效的方法来实现这一点?
如果可能,也请提供示例。
sem_t bin_sem1, bin_sem2;
int count = 1;
int main()
{
int ret;
pthread_t a_thread, b_thread;
ret = sem_init(&bin_sem1, 0, 1);
if (ret != 0)
{
perror("semaphore1 initialization failed\n");
exit(EXIT_FAILURE);
}
ret = sem_init(&bin_sem2, 0, 0);
if (ret != 0)
{
perror("semaphore2 initialization failed\n");
exit(EXIT_FAILURE);
}
ret = pthread_create(&a_thread, NULL, thread_fun1, NULL);
if (ret != 0)
{
perror("Thread1 creation failed");
exit(EXIT_FAILURE);
}
ret = pthread_create(&b_thread, NULL, thread_fun2, NULL);
if (ret != 0)
{
perror("Thread2 creation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for threads to finish\n");
ret = pthread_join(a_thread, NULL);
if (ret != 0)
{
perror("Thread1 join failed");
exit(EXIT_FAILURE);
}
printf("Thread1 joined");
ret = pthread_join(b_thread, NULL);
if (ret != 0)
{
perror("Thread2 join failed");
exit(EXIT_FAILURE);
}
printf("Thread2 joined");
exit(EXIT_SUCCESS);
}
void *thread_fun1(void *arg)
{
int val=0, val2=0;
while (count < 20)
{
sem_wait(&bin_sem1);
sem_getvalue(&bin_sem1, &val);sem_getvalue(&bin_sem2, &val2);
printf("T 1 : after wait : sem 1 = %d, sem 2 = %d\n", val, val2);
printf("T 1 : count = %d\n", count++);
sem_post(&bin_sem2);
sem_getvalue(&bin_sem1, &val);sem_getvalue(&bin_sem2, &val2);
printf("T 1 : after post : sem 1 = %d, sem 2 = %d\n", val, val2);
}
pthread_exit(NULL);
}
void *thread_fun2(void *arg)
{
int val=0, val2=0;
while (count < 20)
{
sem_wait(&bin_sem2);
sem_getvalue(&bin_sem1, &val);sem_getvalue(&bin_sem2, &val2);
printf("\t\t\t\t\t\tT 2 : after wait : sem 1 = %d, sem 2 = %d\n", val, val2);
printf("\t\t\t\t\t\tT 2 : count = %d\n", count++);
sem_post(&bin_sem1);
sem_getvalue(&bin_sem1, &val);sem_getvalue(&bin_sem2, &val2);
printf("\t\t\t\t\t\tT 2 : after post : sem 1 = %d, sem 2 = %d\n", val, val2);
}
pthread_exit(NULL);
}
【问题讨论】:
-
不使用信号量,为什么不使用原子类型?
-
@Linus 一般,因为你不能等待他们。
标签: c multithreading synchronization mutex semaphore