目录
多线程开发的基本API:
参考:https://www.cnblogs.com/xiehongfeng100/p/4620852.html
多线程开发的最基本概念主要包含三点:线程、互斥锁、条件。
对象 | 操作 | Linux Pthread API |
线程 | 创建 | pthread_create |
退出 | pthread_exit | |
等待 | pthread_join | |
互斥锁 | 创建 | pthread_mutex_init |
销毁 | pthread_mutex_destroy | |
加锁 | pthread_mutex_lock | |
解锁 | pthread_mutex_unlock | |
条件 | 创建 | pthread_cond_init |
销毁 | pthread_cond_destroy | |
触发 | pthread_cond_signal | |
广播 | pthread_cond_broadcast | |
等待 | pthread_cond_wait/pthread_cond_timewait |
1、线程:
线程的创建:
#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号
attr参数用于定制各种不同的线程属性,暂可以把它设置为NULL,以创建默认属性的线程。
新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。
线程的退出:
#include <pthread.h>
int pthread_exit(void *rval_ptr);
rval_ptr是一个无类型指针,与传给启动例程的单个参数类似。进程中的其他线程可以通过调用pthread_join函数访问到这个指针。
线程的等待:
#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr);
// 返回:若成功返回0,否则返回错误编号
调用这个函数的线程将一直阻塞,直到指定的线程调用pthread_exit、从启动例程中返回或者被取消。如果例程只是从它的启动例程返回i,rval_ptr将包含返回码。如果线程被取消,由rval_ptr指定的内存单元就置为PTHREAD_CANCELED。
如果对线程的返回值不感兴趣,可以把rval_ptr置为NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态。
查看线程的ID:
#include <pthread.h>
pthread_t pthread_self(void);
// 返回:调用线程的ID
线程的比较:
#include <pthread.h>
int pthread_equal(pthread_t tid1, pthread_t tid2);
// 返回:若相等则返回非0值,否则返回0
线程的脱离:
#include <pthread.h>
int pthread_detach(pthread_t thread);
// 返回:若成功返回0,否则返回错误编号
本函数通常由想让自己脱离的线程使用,就如以下语句:
pthread_detach(pthread_self());
2、互斥锁:
互斥量(mutex)就是一把锁,在访问共享资源前对互斥量进行加锁,在访问完成后释放互斥量上的锁。对互斥量进行加锁后,任何其他试图再次对互斥量加锁的线程将会被阻塞直到当前线程释放该互斥锁。如果释放互斥锁时有多个线程阻塞,所有在该互斥锁上的阻塞线程都会变成可运行状态,第一个变为可运行状态的线程可以对互斥量加锁,其他线程将会看到互斥锁依然被锁住,只能回去等待它重新变为可用。在这种方式下,每次只有一个线程可以向前运行。
在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy。
创建与销毁互斥锁:
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号
要用默认的属性初始化互斥量,只需把attr设置为NULL。
加锁与解锁:
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t mutex);
int pthread_mutex_trylock(pthread_mutex_t mutex);
int pthread_mutex_unlock(pthread_mutex_t mutex);
如果线程不希望被阻塞,它可以使用pthread_mutex_trylock尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞并返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥量,而返回EBUSY。
3、条件:
条件变量是线程另一可用的同步机制。条件变量给多个线程提供了一个会合的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_destroy函数对条件变量进行去除初始(deinitialize)。
创建与销毁条件:
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号
除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。
等待:
#include <pthread.h>
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, cond struct timespec *restrict timeout);
// 返回:若成功返回0,否则返回错误编号
pthread_cond_wait等待条件变为真。
pthread_cond_timedwait函数的工作方式与pthread_cond_wait函数类似,只是多了一个timeout。timeout指定了等待的时间,它是通过timespec结构指定。
触发:
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t cond);
int pthread_cond_broadcast(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号
这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。
4、代码示例:
(1)一个线程的基本创建:
#include <stdio.h>
#include <pthread.h>
void *func(void *arg)
{
static int a = 100;//注意要使用static定义为静态变量,否则在join时会乱掉
printf("t1:%ld\n",(unsigned long)pthread_self());
printf("t1:num is %d\n",*((int *)arg));//先将arg转换为int *型再取内容
pthread_exit((void *)&a);
}
int main()
{
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int ret;
pthread_t t1;
int num = 10;
ret = pthread_create(&t1, NULL, func, (void *)&num);
if(ret == 0){
printf("main:pthread creat success\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
int *pret = NULL;
pthread_join(t1, (void **)&pret);
printf("main:t1 exit is :%d\n",*pret);
return 0;
}
(2)加锁之后的一个简单线程:
#include <stdio.h>
#include <pthread.h>
int g_data = 0;
pthread_mutex_t mutex;
void *func1(void *arg)
{
int i;
pthread_mutex_lock(&mutex);
for(i=0;i<3;i++){
printf("t1:%ld\n",(unsigned long)pthread_self());
printf("t1:num is %d\n",*((int *)arg));
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
void *func2(void *arg)
{
pthread_mutex_lock(&mutex);
printf("t2:%ld\n",(unsigned long)pthread_self());
printf("t2:num is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
void *func3(void *arg)
{
pthread_mutex_lock(&mutex);
printf("t3:%ld\n",(unsigned long)pthread_self());
printf("t3:num is %d\n",*((int *)arg));
pthread_mutex_unlock(&mutex);
}
int main()
{
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int ret;
pthread_t t1;
pthread_t t2;
pthread_t t3;
int num = 10;
pthread_mutex_init(&mutex,NULL);
ret = pthread_create(&t1, NULL, func1, (void *)&num);
if(ret == 0){
printf("main:t1 creat success\n");
}
ret = pthread_create(&t2, NULL, func2, (void *)&num);
if(ret == 0){
printf("main:t2 creat success\n");
}
ret = pthread_create(&t3, NULL, func3, (void *)&num);
if(ret == 0){
printf("main:t3 creat success\n");
}
printf("main:%ld\n",(unsigned long)pthread_self());
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
(3)有锁和条件的一个完整线程,只有g_data为3时,线程一才执行:
#include <stdio.h>
#include <pthread.h>
int g_data = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg)
{
printf("t1:%ld\n",(unsigned long)pthread_self());
printf("t1:num is %d\n",*((int *)arg));
static int cnt = 0;
while(1){
pthread_cond_wait(&cond,&mutex);
printf("================t1 run==================\n");
printf("t1:%d\n",g_data);
g_data = 0;
sleep(1);
if(cnt++ == 3){
exit(0);
}
}
}
void *func2(void *arg)
{
printf("t2:%ld\n",(unsigned long)pthread_self());
printf("t2:num is %d\n",*((int *)arg));
while(1){
pthread_mutex_lock(&mutex);
printf("t2:%d\n",g_data);
g_data++;
if(g_data == 3){
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main()
{
//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int ret;
pthread_t t1;
pthread_t t2;
int num = 10;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
ret = pthread_create(&t1, NULL, func1, (void *)&num);
if(ret == 0){
// printf("main:t1 creat success\n");
}
ret = pthread_create(&t2, NULL, func2, (void *)&num);
if(ret == 0){
// printf("main:t2 creat success\n");
}
// printf("main:%ld\n",(unsigned long)pthread_self());
// while(1){
// printf("main:%d\n",g_data);
// sleep(1);
// }
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
补充:死锁情况,死锁发生的前提条件是有至少两把锁,线程A拿到了锁1的时候想要去拿锁2,线程B拿到了锁2的时候想要去拿锁1,此时就会造成死锁的情况。