简体   繁体   中英

lvalue required as unary '&" operand

I have a problem with my project which is supposed to add up every line using a thread then sum it all, but I'm getting an error that says lvalue required as unary '&" operand

pthread_create(&tid, NULL, &sum_line(0), NULL);

I've tried some thing but couldn't solve it, any ideas? Thanks

#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());
}

Pass a pointer to function to pthread_create()

Write just sum_line , not &sum_line(0) .

The pthread_create() function expects a pointer to the thread function — ie the function name — and not the result of calling the function. The pthread_create() function will arrange for the new thread to call the function, but it needs a function pointer.

Also, the signature for a thread function must be:

void *function(void *arg);

The function should also return a value — add return 0; before the close brace.

You pass a null pointer to the function; you can't expect that to work as int nr_line . You'll need to do some fancy footwork to get a number to the function. There are two main options:

Either

int nr_line = 247;

pthread_create(&tid, NULL, sum_line, &nr_line);

The function then looks like:

void *sum_line(void *arg)
{
    int nr_line = *(int *)arg;
    …
    return 0;
}

Just make sure each thread gets a pointer to a different object when you start multiple threads.

Or

uintptr_t nr_line = 247;
pthread_create(&tid, NULL, sum_line, (void *)nr_line);

Or:

int nr_line = 247;
pthread_create(&tid, NULL, sum_line, (void *)(uintptr_t)nr_line);

and the function then looks like:

void *sum_line(void *arg)
{
    int nr_line = (uintptr_t)arg;
    …
    return 0;
}

The double cast avoids compiler warnings about converting an integer of a different size to a pointer.

Note that pthread_create() will call the function as if it is void *function(void *args) , so passing it any other type of function pointer, even if cast with (void (*)(void *)) , is cheating and leads to undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM