C++中线程的使用方法

在C++中,可以使用以下两种方式创建线程:

使用pthread库

C++中可以使用pthread库来创建线程。pthread库是一个开源的线程库,可以用来管理和创建线程。以下是一个使用pthread库创建线程的示例代码:


#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; 

}

在上面的示例中,我们首先定义了一个名为thread_func的函数,该函数是线程要执行的函数。在主函数中,我们使用pthread_create函数创建了一个新线程,该函数接受四个参数:线程标识符、线程属性、线程函数和参数。最后,我们使用pthread_join函数等待线程执行完毕。

使用C++11标准库

在C++11标准库中,提供了一个名为std::thread的类,可以用来创建线程。以下是一个使用C++11标准库创建线程的示例代码:


#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; 

}

在上面的示例中,我们首先定义了一个名为thread_func的函数,该函数是线程要执行的函数。在主函数中,我们使用std::thread类创建了一个新线程,该函数的参数是线程要执行的函数。最后,我们使用join函数等待线程执行完毕。

猜你喜欢

转载自blog.csdn.net/qq_50942093/article/details/131456070