【发布时间】:2019-04-25 15:52:41
【问题描述】:
我最初为我的斐波那契变量数组设置了一个全局变量,但发现这是不允许的。我需要进行基本的多线程处理并处理竞争条件,但我无法在 pthread create 中将 int 作为 void 参数提供。我试过使用一个没有运气的常量指针。出于某种奇怪的原因,void* 通过了第一个布尔测试,但没有通过 else if:
$ gcc -o fibonacci fibonacci.c
fibonacci.c:22:16: warning: comparison between pointer and integer ('void *' and 'int')
else if (arg == 1)
~~~ ^ ~
1 warning generated.
我的代码一团糟,我真的很困惑,因为我已经重写了很多次。如果我将线程运行函数中的所有参数转换为整数,我会得到一个分段错误 11,这是有道理的。所有通过地址传递 i 索引并取消引用它的尝试都失败了,因为它是一个 void 并且不能用作 int。你能推荐点别的吗?
#include<stdio.h> //for printf
#include<stdlib.h> //for malloc
#include<pthread.h> //for threading
#define SIZE 25 //number of fibonaccis to be computed
int *fibResults; //array to store fibonacci results
void *run(void *arg) //executes and exits each thread
{
if (arg == 0)
{
fibResults[(int)arg] = 0;
printf("The fibonacci of %d= %d\n", (int)arg, fibResults[(int)arg]);
pthread_exit(0);
}
else if (arg == 1)
{
fibResults[(int)arg] = 1;
printf("The fibonacci of %d= %d\n", (int)arg, fibResults[(int)arg]);
pthread_exit(0);
}
else
{
fibResults[(int)arg] = fibResults[(int)arg -1] + fibResults[(int)arg -2];
printf("The fibonacci of %d= %d\n", (int)arg, fibResults[(int)arg]);
pthread_exit(0);
}
}
//main function that drives the program.
int main()
{
pthread_attr_t a;
fibResults = (int*)malloc (SIZE * sizeof(int));
pthread_attr_init(&a);
for (int i = 0; i < SIZE; i++)
{
pthread_t thread;
pthread_create(&thread, &a, run,(void*) &i);
printf("Thread[%d] created\t", i);
fflush(stdout);
pthread_join(thread, NULL);
printf("Thread[%d] joined & exited\t", i);
}
return 0;
}
【问题讨论】:
标签: c casting int pthreads void