线程的使用在软件开发中是十分普遍的,本文总结了两种常用的线程API接口:POSIX线程和CPP11线程。

1 POSIX线程

创建线程

int pthread_create(pthread_t* tid, const phtread_attr_t* attr,
		   void* (*start_routine)(void*), void* arg);

停止线程

int pthread_cancel(pthread_t tid);

获取当前线程id

pthread_t pthread_self();

等待线程

int pthread_join(pthread_t tid, void** retval);

信号处理

// 向线程发送信号
int pthread_kill(pthread_t thread, int sig);
// 检查或修改被屏蔽的信号
int pthread_sigmask(int how, const sigset_t* set, sigset_t* oldset);

互斥量

int pthread_mutex_init(pthread_mutex_t* restrict mutex,
		       const pthread_mutexattr_t* restrict attr);

int pthread_mutex_destroy(pthread_mutex_t* mutex);

int pthread_mutex_lock(pthread_mutex_t* mutex);

int pthread_mutex_trylock(pthread_mutex_t* mutex);

int pthread_mutex_unlock(pthread_mutex_t* mutex);

条件变量

int pthread_cond_destroy(pthread_cond_t* restrict cond,
			 const pthread_condattr_t* restrict attr);

int pthread_cond_init(pthread_cond_t* cond);

int phread_cond_wait(pthread_cond_t* cond, pthread_mutex_t* mutex);

int pthread_cond_signal(pthread_cond_t* cond);

int pthread_cond_broadcast(pthread_cond_t* cond);

以上接口在编译时额外参数 -lpthread

这里列举的只是一小部分,在linux中使用 apropos pthread 命令能够获得更多 pthread 相关接口。

2 CPP11线程

创建线程

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

获取线程id

std::thread::id std::thread::get_id() const noexcept;

// 获取当前线程id
std::thread::id std::this_thread::get_id() noexcept;

互斥量

void std::mutex::lock();

bool std::mutex::trylock();

void std::mutex::unlock();

// mutex with timeout
bool std::timed_mutex::try_lock_for(
		       const std::chrono::duration<Rep, Period>& timeout_duration);

bool std::timed_mutex::try_lock_until(
		       const std::chrono::time_point<Clock, Duration>& timeout_time);

// 其他种类的互斥锁
std::recursive_mutex;
std::recursive_timed_mutex;

// 自动加锁解锁
template< class Mutex >
class lock_guard;

条件变量

void std::condition_variable::wait(std::unique_lock<std::mutex>& lock);

template< class Predicate >
void std::condition_variable::wait(std::unique_lock<std::mutex>& lock,
				   Predicate pred);

void std::condition_variable::notify_one() noexcept;

void std::condition_variable::notify_all() noexcept;