[英]lvalue required as unary '&" operand
我的項目有一個問題,應該使用一個線程將每一行加起來然后求和,但是我遇到一個錯誤,說左值要求為一元'&“操作數
pthread_create(&tid,NULL,&sum_line(0),NULL);
我已經嘗試過一些東西,但是無法解決,有什么想法嗎? 謝謝
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static void * sum_line(int nr_line);
int Sum;
int A[4][4];
int main() {
pthread_t tid;
Sum=0;
printf("\nOrig thread tid(%d) Sum=%d", pthread_self(), Sum);
pthread_create(&tid, NULL, &sum_line(0), NULL);
printf("\nChild thread was created tid(%d)", tid);
pthread_join(tid,NULL);
printf("\nOrig thread tid(%d)-->Child thread ended tid(%d) Sum=%d",pthread_self(), tid, Sum);
printf("\n");
}
static void * sum_line(int nr_line) {
int i;
for(i=0;i<4;i++) {
Sum=Sum+A[i];
printf("\nChild thread tid(%d), i=%d, Sum=%d",pthread_self(),i,Sum);
sleep(2);
}
printf("\nChild thread tid(%d)--> ending", pthread_self());
}
pthread_create()
只寫sum_line
而不是&sum_line(0)
。
pthread_create()
函數需要一個指向線程函數的指針(即函數名稱),而不是調用該函數的結果。 pthread_create()
函數將安排新線程調用該函數,但它需要一個函數指針。
另外,線程函數的簽名必須為:
void *function(void *arg);
該函數還應該返回一個值-加return 0;
在大括號之前。
您將空指針傳遞給該函數; 您不能指望它可以像int nr_line
工作。 您需要做一些花哨的步法才能為函數添加一個數字。 有兩個主要選項:
int nr_line = 247;
pthread_create(&tid, NULL, sum_line, &nr_line);
該函數如下所示:
void *sum_line(void *arg)
{
int nr_line = *(int *)arg;
…
return 0;
}
只要確保在啟動多個線程時每個線程都有一個指向不同對象的指針即可。
uintptr_t nr_line = 247;
pthread_create(&tid, NULL, sum_line, (void *)nr_line);
要么:
int nr_line = 247;
pthread_create(&tid, NULL, sum_line, (void *)(uintptr_t)nr_line);
然后該函數如下所示:
void *sum_line(void *arg)
{
int nr_line = (uintptr_t)arg;
…
return 0;
}
double強制轉換避免了編譯器有關將不同大小的整數轉換為指針的警告。
請注意pthread_create()
會像調用void *function(void *args)
一樣調用函數,因此,即使使用(void (*)(void *))
強制轉換,也會將其他任何類型的函數指針傳遞給該函數導致不確定的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.