如何将int传递为“ void *”线程启动功能? [英] How to pass an int as "void *" to thread start function?
问题描述
我本来是斐波那契变量数组的全局变量,但发现这是不允许的。我需要进行基本的多线程处理并处理竞争条件,但是我无法克服在pthread create中将int作为void参数的问题。我尝试使用没有运气的常量指针。出于某些奇怪的原因,void *通过了第一个布尔测试,但在以下情况下没有通过:
I originally had a global variable for my fibonacci variable array, but found out that is not allowed. I need to do elementary multithreading and handle race conditions, but I can't get past feeding an int as a void argument in pthread create. I've tried using a constant pointer with no luck. For some strange reason the void* gets past the first boolean test but not the 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.
我的代码一团糟,我真的很困惑,因为我已经重写了很多次了。如果将线程运行函数中的所有args转换为int,则会得到分段错误11,这很有意义。所有尝试通过地址传递i索引并对其取消引用的尝试均以失败告终,因为它是空值,不能用作整数。您还能提出其他建议吗?
My code is a mess and I am getting really confused because I have rewritten it so many times. If I cast all the args in my thread run function as ints I get a segmentation fault 11, which makes sense. All attempts at passing the i index by address and dereferencing it have failed, as it is a void and can't be used as an int. Can you suggest something else?
#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;
}
推荐答案
在 run()
函数,您应该执行以下操作:
In the run()
function you should do:
void *run(void *ptrarg) //executes and exits each thread
{
int arg = *((int *)ptrarg);
if (arg == 0)
....
....
和其余的 run()
,您无需投放 arg
。将(int)arg
替换为 arg
。
and in rest of the run()
, you don't need to cast the arg
. Replace (int)arg
with arg
.
编辑:
创建线程时将参数传递给 fun()
的方式可能会导致竞赛条件,因为所有线程都将使用相同的指针。请检查@Jonathan的答案以避免出现此问题。
The way you are passing the argument to fun()
while creating threads may cause race condition because all threads will be using same pointer. Check the @Jonathan's answer to avoid this problem.
这篇关于如何将int传递为“ void *”线程启动功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!