【发布时间】:2016-04-22 17:03:09
【问题描述】:
我是 Linux 中并发和线程概念的新手,我试图解决一个相对简单的问题。我创建了两个线程,它们运行相同的函数,增加一个全局变量。我真正想从我的程序中增加该变量,也就是说,在每个步骤中,增加该变量的线程会在屏幕上打印一条消息,因此预期的输出应该如下所示:
Thread 1 is incrementing variable count... count = 1
Thread 2 is incrementing variable count... count = 2
Thread 1 is incrementing variable count... count = 3
Thread 2 is incrementing variable count... count = 4
等等。
我尝试了一个带有信号量的实现,以确保互斥,但结果类似于:
Thread 2 is incrementing variable count... count = 1
Thread 2 is incrementing variable count... count = 2
Thread 2 is incrementing variable count... count = 3
Thread 2 is incrementing variable count... count = 4
Thread 2 is incrementing variable count... count = 5
Thread 1 is incrementing variable count... count = 6
Thread 1 is incrementing variable count... count = 7
Thread 1 is incrementing variable count... count = 8
Thread 1 is incrementing variable count... count = 9
Thread 1 is incrementing variable count... count = 10
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
int count = 0;
sem_t mutex;
void function1(void *arg)
{
int i = 0;
int *a = (int*) arg;
while (i < 10)
{
sem_wait(&mutex);
count++;
i++;
printf("From the function : %d count is %d\n",*a,count);
sem_post(&mutex);
}
}
int main()
{
pthread_t t1,t2;
int a = 1;
int b = 2;
pthread_create(&t1,NULL,(void *)function1,&a);
pthread_create(&t2,NULL,(void *)function1,&b);
sem_init(&mutex,0,1);
pthread_join(t2,NULL);
pthread_join(t1,NULL);
sem_destroy(&mutex);
return 0;
}
我现在最大的问题是,如何实现线程之间的这种交替?我得到了互斥,但仍然缺少交替。也许我对信号量的使用缺乏深入的了解,但如果有人能向我解释这一点,我将不胜感激。 (我看过几门关于这个主题的课程,即Linux信号量,并发和线程,但那里的信息不够令人满意)
【问题讨论】:
标签: linux multithreading concurrency semaphore