1

I tried to compile a simple POSIX example in CLIon ide, but it doesn`t know about pthread library, I think... Here is the code:

void *func1()
{
    int i;
    for (i=0;i<10;i++) { printf("Thread 1 is running\n"); sleep(1); }
}
void *func2()
{
    int i;
    for (i=0;i<10;i++) { printf("Thread 2 is running\n"); sleep(1); }
}

int result, status1, status2;
pthread_t thread1, thread2;

int main()
{
    result = pthread_create(&thread1, NULL, func1, NULL);
    result = pthread_create(&thread2, NULL, func2, NULL);
    pthread_join(thread1, &status1);
    pthread_join(thread2, &status2);
    printf("\nПотоки завершены с %d и %d", status1, status2);

    getchar();
    return 0;
}

It is known, that this code is correct, because it's taken from the example in the book. So Clion marks second arguments of pthread_join function as a mistake, giving this error:

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

I suppose, thet the problem is in the CmakeList. Here is my current CMakeList:

cmake_minimum_required(VERSION 3.3)
project(hello_world C CXX)



set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pthread")



set(SOURCE_FILES main.cpp)
add_executable(hello_world ${SOURCE_FILES})
Hayt
  • 5,210
  • 30
  • 37
palladian
  • 11
  • 1
  • 2

1 Answers1

3

Your function signature is wrong for the callback to pthread.

func1 and func2 have the signature void* (*)(). This means returns a void* and has no parameters

But pthread wants void* (*)(void*) Here you also have a void* as parameter.

so your functions should look like this:

void *func1(void* param) ...

You don't have to use the parameter but it has to be there in the declaration.

Note:

To tell cmake to link against pthread you should use this:

find_package( Threads REQUIRED ) 
add_executable(hello_world ${SOURCE_FILES})
target_link_libraries( hello_world Threads::Threads )

See here: How do I force cmake to include "-pthread" option during compilation?

Community
  • 1
  • 1
Hayt
  • 5,210
  • 30
  • 37
  • Well... the problem was not about the functions` signature, but about the arguments status1 and status2 in pthread_join. I edited my CMakeList as you`ve written, but it didn`t effect. – palladian Oct 20 '16 at 03:30
  • The bottom note helped me in a slightly different scenario, so thanks! – Yoav Feuerstein Jan 01 '17 at 12:46