强制转换到指针错误多线程程序



这是一个输出素数的多线程程序。用户运行程序并在命令行中输入一个数字。它创建了一个单独的线程,输出小于或等于用户输入的数字的所有素数。

我有一个错误:警告:从不同大小的整数转换为指针[-Wint到指针转换]我很接近,但我已经盯着这个看了一段时间了。我想我会得到一些反馈。

我该怎么解决这个问题?这里指的是空白:

(void *)count);

这是所有的代码:

#include <stdio.h>
#include <pthread.h>
int N = 100;  //number of promes to be generated
int prime_arr[100000] = {0};  //prime arrray
void *printprime(void *ptr)  //thread function
{
int j, flag;
int i = (int)(long long int)ptr;  //getting thread number
//for thread 0, we check for all primes 0,4,8,12
//for thread 1, we check for all primes 1,5,9,13
while (i < N) {  //while number in range
flag = 0;  //check if i has factor
for (j = 2; j <= i / 2; j++)  //factor can be at max i/2 value
{
if (i % j == 0)  //factor found
{
flag = 1;
break;
}
}
if (flag == 0 && (i > 1))  //prime found, no factor
{
prime_arr[i] = 1;
}
i += 4;  //increase by interval of 4
}
}
int main()
{
printf("Enter N: ");
scanf("%d", &N);  //input N
pthread_t tid[4] = {0};  //create an array of 4 threads
int count = 0;
for (count = 0; count < 4; count++)  //initialize threads and start
{
printf("rn CREATING THREADS %d", count);
pthread_create(&tid[count], NULL, printprime,(void *)count);  //count is passed as argument, target = printprime
}
printf("n");
for (count = 0; count < 4; count++)
{
pthread_join(tid[count], NULL);  //while all thread havent finished
}
int c = 0;
for (count = 0; count < N; count++)  //print primes
if (prime_arr[count] == 1)
printf("%d ", count);
printf("n");
return 0;
}

这里将count强制转换为不兼容类型的void*

pthread_create(&tid[count], NULL, printprime, (void*) count);

在这里,你试图不正确地将其转换回int:

int i = (int)(long long int)ptr;

我建议创建工作包tasks,您可以使用它,并可能将其强制转换为void*和返回。

示例:

#include <pthread.h>
#include <stdio.h>
typedef struct {
pthread_t tid;
int count;
} task_t;
void *printprime(void *ptr) {
task_t *task = ptr;
task->count += 10;       // do some work
return NULL;
}
#define TASKS (4)
int main() {
task_t tasks[TASKS] = {0};              // an array of tasks
for (int count = 0; count < TASKS; ++count) {
tasks[count].count = count;         // fill the task with some job
pthread_create(&tasks[count].tid, NULL, printprime, &tasks[count]);
}
// join and take care of result from all threads
for (int count = 0; count < TASKS; ++count) {
pthread_join(tasks[count].tid, NULL);
printf("task %d value = %dn", count, tasks[count].count);
}
}

演示

使用uintptr_tintptr_t而不是int

从技术上讲,这是用于将指针存储在整数中,而不是用于将整数存储在指针中。所以这不完全是犹太洁食。但这仍然是一种常见的做法。

为了正确地执行此操作,您需要(静态或动态(为每个线程分配一个变量,并将该变量的地址传递给线程。

最新更新