在下面的代码中,我尝试使用线程顺序计算 x1 和 x2 的值。(在实际情况下,x1 和 x2 将是大计算)但等待两个线程使用 while 循环计算各个变量的值正在成为处理器成本高。问题是,我希望两个线程并行运行,但是两个线程的循环应该同样序列化(意味着应该在一次调用中运行一次)。因此,有什么方法可以删除这些 while 循环并串行获取结果。我对使用信号量和互斥量感到很困惑,因为 x1 和 x2 是相互独立的?请帮忙。提前致谢。
#include <stdio.h>
#include <pthread.h>
pthread_t pth1,pth2;
//Values to calculate
int x1 = 0, x2 = 0;
//Values for condition
int cond1 = 0,cond2 = 0;
void *threadfunc1(void *parm)
{
for (;;) {
// Is this while loop is very costly for the processor?
while(!cond1) {}
x1++;
cond1 = 0;
}
return NULL ;
}
void *threadfunc2(void *parm)
{
for (;;) {
// Is this while loop is very costly for the processor?
while(!cond2) {}
x2++;
cond2 = 0;
}
return NULL ;
}
int main () {
pthread_create(&pth1, NULL, threadfunc1, "foo");
pthread_create(&pth2, NULL, threadfunc2, "foo");
int loop = 0;
while (loop < 10) {
// iterated as a step
loop++;
printf("Initial : x1 = %d, x2 = %d\n", x1, x2);
cond1 = 1;
cond2 = 1;
// Is this while loop is very costly for the processor?
while(cond1) {}
while(cond2) {}
printf("Final : x1 = %d, x2 = %d\n", x1, x2);
}
pthread_cancel(pth1);
pthread_cancel(pth2);
return 1;
}