How to use threads in C++

In C++, threads can be created in two ways:

Use the pthread library

C++ can use the pthread library to create threads. The pthread library is an open source thread library that can be used to manage and create threads. The following is a sample code for creating a thread using the pthread library:


#include <pthread.h> 

#include <iostream> 

 

void* thread_func(void* arg) { 

    std::cout << "Thread function running" << std::endl; 

    return nullptr; 

} 

 

int main() { 

    pthread_t thread; 

    int ret = pthread_create(&thread, nullptr, thread_func, nullptr); 

    if (ret != 0) { 

        std::cerr << "Failed to create thread" << std::endl; 

        return 1; 

    } 

    pthread_join(thread, nullptr); 

    return 0; 

}

In the above example, we first defined a function called thread_func which is the function to be executed by the thread. In the main function, we create a new thread using the pthread_create function, which accepts four parameters: thread identifier, thread attributes, thread function, and parameters. Finally, we wait for the thread to finish executing using the pthread_join function.

Using the C++11 standard library

In the C++11 standard library, a class called std::thread is provided, which can be used to create threads. The following is a sample code for creating threads using the C++11 standard library:


#include <thread> 

#include <iostream> 

 

void thread_func() { 

    std::cout << "Thread function running" << std::endl; 

} 

 

int main() { 

    std::thread thread(thread_func); 

    thread.join(); 

    return 0; 

}

In the above example, we first defined a function called thread_func which is the function to be executed by the thread. In the main function, we create a new thread using the std::thread class, and the parameter of this function is the function to be executed by the thread. Finally, we use the join function to wait for the thread to finish executing.

Guess you like

Origin blog.csdn.net/qq_50942093/article/details/131456070