我正在尝试获得循环中迭代的总计数,循环被分解为线程,在C中。使用全局变量(锁/解锁),全局varNUM_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++;
}
}
}
tsum输出为零。这是关于在pthread_create中来回转换传递的指针吗?或者使用这种方法是完全错误的?
发布于 2018-06-03 05:29:47
由于++
具有比一元*
更高的运算符优先级,因此您将递增计数器,而不是递增计数器所指向的数组元素。如果您更改了行
*counter++;
要阅读以下两者之一
(*counter)++;
或
*counter += 1;
那么tsum
最终会像你预期的那样变成10000000000。
这种语言是这样定义的,因为更常见的方式是编写如下内容
while (*p) *q++ = *p++;
您希望指针递增的位置。
https://stackoverflow.com/questions/50661293
复制相似问题