invalid conversion from ‘void* (*)()’ to ‘void* (*)(void*)’

Why can’t you stop buying 618?From the technical dimension to explore>>>

void* thread_func2(void* arg) {
    pid_t pid = getpid();
    pthread_t tid = pthread_self();
    printf("%s pid: %u, tid: %u (0x%x)\n", (char*)arg, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
    while(1) {
        printf("%s running\n", (char*)(arg));
        sleep(1);
    }
    return nullptr;
}

int main()
{
	pthread_t tid2;
    if (pthread_create(&tid2, NULL, (void *)thread_func2, "new thread:") != 0) {
        printf("pthread_create error.");
        exit(EXIT_FAILURE);
    }
    return 0;
	}

The above code compiles in Linux environment with error:

error: invalid conversion from ‘void*’ to ‘void* ()(void)’

pthread_ The prototype of the create function is as follows:

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

The third parameter: a function pointer with a return value of void *, and the parameter of the function pointer is void *

The fourth parameter: the parameter of the function, which needs to be converted to a void * type pointer

Check the definition of thread function: the definition of thread function completely meets the requirements of thread creation function. Theoretically, there should be no error. Check thread function call: if (pthread)_ create(& tid2, NULL, (void *)thread_ func2, “new thread:”) != 0): the third parameter: no need to cast. The fourth parameter type is actually const char *, is it caused by the wrong parameter type. According to the above guess, after the modification is completed, compile again and succeed


It is worth noting that there will be no errors in GCC compilation, but there will be problems with G + +. The reason is that the C compiler allows implicit conversion of a general pointer to any type of pointer, while C + + does not

Similar Posts: