我试图在一个循环中得到迭代的总计数,这个循环被分解为线程,在C中.使用全局变量(锁定/解锁),全局变量[NUM_THREADS],两者都有效(第一个很多)慢一点); 但是下面的代码不起作用:
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#define THREADS 8
void *loop(void *ptr);
int main()
{
clock_t ts = clock();
pthread_t th[THREADS];
long long lsum[THREADS] = {0};
for (int t = 0; t < THREADS; t++)
{
pthread_create(&th[t], NULL, loop, (void *)&lsum[t]);
}
for (int i = 0; i < THREADS; i++)
{
pthread_join(th[i], NULL);
}
long long tsum = 0;
for (int i = 0; i < THREADS; i++)
{
tsum += lsum[i];
}
clock_t te = clock();
printf("%.3f%s\n", (float)(te - ts) / CLOCKS_PER_SEC, " Seconds");
printf("%lld", tsum);
}
void *loop(void *ptr)
{
long long *counter = ptr;
for (int i = 0; i < 1000000 / THREADS; i++)
{
for (int j = 0; j < 10000; j++)
{
i - (i / (j + 1)) + j *j;
*counter++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
tsum输出为零.这是关于在pthread_create中来回传递指针的东西吗?或者使用这种方法都错了?
因为++运算符优先级高于一元*,所以增量计数器,而不是计数器指向的数组元素.如果你改变了这条线
*counter++;
Run Code Online (Sandbox Code Playgroud)
阅读其中之一
(*counter)++;
Run Code Online (Sandbox Code Playgroud)
要么
*counter += 1;
Run Code Online (Sandbox Code Playgroud)
然后tsum将如预期的那样结束100亿.
语言是以这种方式定义的,因为编写类似的东西更常见
while (*p) *q++ = *p++;
Run Code Online (Sandbox Code Playgroud)
你想要指针增加的地方.