pthread 简介
pthread 是 POSIX 线程(POSIX Threads)的简称,它是 POSIX 标准中定义的线程接口规范。pthread 库提供了一系列函数,用于创建、销毁、同步和管理线程。在类 Unix 系统(如 Linux、macOS)中,pthread 库被广泛使用,是实现多线程编程的重要工具。
基本使用方法
线程创建
使用 pthread_create 函数来创建一个新线程。其函数原型如下:
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
thread:指向 pthread_t 类型变量的指针,用于存储新创建线程的标识符。
attr:线程属性,通常设为 NULL,使用默认属性。
start_routine:指向线程函数的指针,线程启动后将执行该函数。
arg:传递给线程函数的参数。
#include <stdio.h>
#include <pthread.h>
// 线程函数
void* thread_function(void* arg) {
printf("This is a thread, argument: %d\n", *(int*)arg);
return NULL;
}
int main() {
pthread_t thread;
int arg = 10;
// 创建线程
if (pthread_create(&thread, NULL, thread_function, &arg)!= 0) {
perror("Failed to create thread");
return 1;
}
printf("Thread created successfully\n");
// 等待线程结束
if (pthread_join(thread, NULL)!= 0) {
perror("Failed to join thread");
return 1;
}
printf("Thread joined successfully\n");
return 0;
}
线程等待
使用 pthread_join 函数等待一个线程结束。函数原型:
int pthread_join(pthread_t thread, void **retval);
thread:要等待的线程标识符。
retval:用于接收线程函数的返回值,通常设为 NULL。
线程销毁
可以使用 pthread_cancel 函数来取消一个线程。函数原型:
int pthread_cancel(pthread_t thread);
thread:要取消的线程标识符。
注意,被取消的线程需要有相应的清理机制,否则可能会导致资源泄漏。
传参实例
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
int j = 2;
void* pthread_fun(void *arg)
{
while(j--)
{
cout << " in pthread_task" << endl;
cout << *(int*)arg << endl;
sleep(1);
}
// 线程返回一个整数值
int* result = new int(42);
return static_cast<void*>(result);//pthread_exit(reinterpret_cast<void*>(result));
}
int main()
{
int ret = 0;
pthread_t tid = 0;
int argsend = 99;
int i = 3;
ret = pthread_create(&tid, NULL, pthread_fun, &argsend);
if(ret != 0)
{
cout << " pthread_create error" << endl;
return -1;
}
while(i--)
{
cout << "pthread _create success" << endl;
sleep(2);
//等待回收资源
}
void* ret1;
// 阻塞式等待线程结束,并获取返回值
if (pthread_join(tid, &ret1) != 0) {
std::cerr << "Failed to join thread." << std::endl;
return 1;
}
// 处理线程的返回值
int* result = static_cast<int*>(ret1);
std::cout << "Thread returned: " << *result << std::endl;
// 释放动态分配的内存
delete result;
return 0;
}
线程同步
多线程编程中,线程同步是至关重要的。pthread 提供了多种同步机制,如互斥锁、条件变量、信号量等。
互斥锁
互斥锁用于保证同一时刻只有一个线程能够访问共享资源。使用 pthread_mutex_t 类型来定义互斥锁,相关函数有:
pthread_mutex_init:初始化互斥锁。
pthread_mutex_lock:加锁,若锁已被占用则线程阻塞。
pthread_mutex_unlock:解锁。
pthread_mutex_destroy:销毁互斥锁。
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_variable = 0;
void* increment(void* arg) {
for (int i = 0; i < 1000; ++i) {
pthread_mutex_lock(&mutex);
shared_variable++