這是一個輸出素數的多執行緒程式。用戶運行程式并在命令列中輸入一個數字。它創建一個單獨的執行緒,輸出所有小于或等于用戶輸入的數字的素數。
我有一個錯誤:警告:從不同大小的整數轉換為指標 [-Wint-to-pointer-cast] 我已經很接近了,但我已經盯著這個看了一段時間了。我以為我會得到一些反饋。
我怎樣才能解決這個問題?它指的是這里的空白:
(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("\r\n 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;
}
uj5u.com熱心網友回復:
使用 auintptr_t或 aintptr_t代替int.
從技術上講,這是用于將指標存盤在整數中,而不是用于將整數存盤在指標中。所以它不完全是猶太潔食。但這仍然是一種常見的做法。
要正確執行此操作,您需要(靜態或動態)為每個執行緒分配一個變數,并將該變數的地址傳遞給執行緒。
uj5u.com熱心網友回復:
在這里,您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 = %d\n", count, tasks[count].count);
}
}
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/420516.html
標籤:
上一篇:為什么從2開始回圈?
