c++ 多线程

182 阅读1分钟

std::thread VS pthread

多平台的情况下,pthread更加稳定,推荐使用pthread

pthread 使用方法

#include <pthread.h> 

void* fn(void* v) { // thread}


// 创建线程,
pthread_t thrdid;
pthread_create(&thrdid, NULL, &fn, NULL);

pthread_exit(NULL);  // 确保线程不会随着主线程的退出而结束


// sleep
std::this_thread::sleep_for(std::chrono::seconds(1));

互斥量

// mutex
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;

// lock
pthread_mutex_lock(&mut);
.........
// unlock
pthread_mutex_unlock(&mut);

atexit

atexit(endtask);

在所有任务都执行完后,执行endtask这个函数

是指所有的线程都结束