Simple pthread! C++

前端 未结 6 1083
生来不讨喜
生来不讨喜 2021-02-07 02:25

I have no idea why this doesn\'t work

#include 
#include 
using namespace std;

void *print_message(){

    cout << \"Thre         


        
6条回答
  •  醉话见心
    2021-02-07 03:10

    Because the main thread exits.

    Put a sleep in the main thread.

    cout << "Hello";
    sleep(1);
    
    return 0;
    

    The POSIX standard does not specify what happens when the main thread exits.
    But in most implementations this will cause all spawned threads to die.

    So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread_join();

    #include 
    #include 
    using namespace std;
    
    #if defined(__cplusplus)
    extern "C"
    #endif
    void *print_message(void*)
    {
        cout << "Threading\n";
    }
    
    
    
    int main() 
    {
        pthread_t t1;
    
        pthread_create(&t1, NULL, &print_message, NULL);
        cout << "Hello";
    
        void* result;
        pthread_join(t1,&result);
    
        return 0;
    }
    

提交回复
热议问题