【发布时间】:2016-06-26 12:55:41
【问题描述】:
只是线程的初学者,我只是在做一个涉及这两个线程的任务。
#include <stdio.h>
#include <pthread.h>
int count = 0;
void waitFor(unsigned int secs)
{
unsigned int retTime = time(0) + secs;
while(time(0) < retTime);
}
void func1(void * args)
{
printf("In func1 ...\n");
long i = 0;
while(1){
i++;
if(count == 1)
break;
}
printf("The total number counted is: %ld \n", i);
count = 0;
i = 0;
}
void func2(void * args)
{
printf("In func2 ...\n");
waitFor(3);
count = 1;
}
int main()
{
pthread_t th1, th2;
int j = 0;
while(j++ < 4){
printf("\nRound:\t%d\n", j);
pthread_create(&th1, NULL, (void*)func1,NULL);
pthread_create(&th2, NULL, (void*)func2, NULL);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
waitFor(3);
}
return 0;
}
我已经阅读了各种参考资料,据我了解,pthread_join() 意味着如果有 2 个或更多线程,那么它们将等待一个线程完成其执行,然后下一个线程将开始执行,依此类推。
但是当我运行这个程序时,在执行 pthread_join(th1) 的那一刻,两个线程都被创建并“同时”执行。这是怎么回事? 输出:
Round: 1
In func2 ...
In func1 ...
The total number counted is: 897651254
Round: 2
In func1 ...
In func2 ...
The total number counted is: 1051386065
........
我的目标是并行运行这 2 个线程。现在, join 似乎可以做到这一点;还是我哪里出错了?
而且我已经读到 C 中的线程不首选使用 volatile。那么有什么方法可以使用 count 作为线程 2 到 1 的信号吗?
【问题讨论】:
-
您在哪里读到“如果有 2 个或更多线程,那么它们将等待一个线程完成其执行,然后下一个线程将开始执行”? Pthread_join 只是等待您作为参数提供的线程终止。是什么让您认为您的踏板是在您调用 pthread_join 时创建的?您的线程是使用 pthread_create 创建和启动的。
-
需要保护对共享变量(此处为
count)的并发读/写访问。这通常使用互斥锁来完成。请参阅上面的pthread_mutex_*()函数。 -
@alk,如果我在 func2 中锁定计数,在 func2 解锁计数之前,我的整个 func1 不会停止吗?或者直到func1中的'count'语句被执行并等待func2解锁它?那么这意味着没有并发对吗?
-
如果任何答案解决了您的问题,请单击大复选框接受它作为答案。这将向社区表明您找到了解决方案,并将给您和回答者一些声誉。
标签: c multithreading pthreads volatile