【发布时间】:2019-11-02 15:56:07
【问题描述】:
为了更快的计算,尝试让我的方法由 4 个线程并行化。无论我是否期望并发操作和单个变量,线程都在进行 4 次单独计算。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static int x, j=5;
void *print_count (void *dummy)
{
for(int i=0;i<1000;i++){
x+=j;
}
}
int main ()
{
pthread_t p1, p2, p3, p4;
pthread_create (&p1, NULL, print_count, NULL);
pthread_create (&p2, NULL, print_count, NULL);
pthread_create (&p3, NULL, print_count, NULL);
pthread_create (&p4, NULL, print_count, NULL);
pthread_join (p1, NULL);
pthread_join (p2, NULL);
pthread_join (p3, NULL);
pthread_join (p4, NULL);
printf("Actual output: %d \nExpected output: 5000\n", x);
return 0;
}
我希望输出 5000,因为增量为 5 并循环 1000 次。 但实际输出首先不是静态的,它总是在变化,接近 5000 的 4 倍,因为线程是单独计算 print_count。
谢谢
【问题讨论】:
标签: c concurrency parallel-processing pthreads posix