参考了很多博主的代码,https://blog.csdn.net/qq_28114615/article/details/88367016中博主对互斥锁及死锁讲得很详细且易懂。但其中代码的实现用的是C++11的新特性thread而不是pthread.h。
pthread.h的具体应用及参数的传递可以参考https://www.runoob.com/cplusplus/cpp-multithreading.html以及https://blog.csdn.net/u013894427/article/details/83827173。
本篇中的代码整体参考https://www.cnblogs.com/zhangjiansheng/p/9332799.html,并进行了相应的修改。作出了注释
#include<iostream>
#include <pthread.h>
#include "unistd.h"
#define THREAD_NUMBER 3 /*线程数*/
#define REPEAT_NUMBER 4 /*每个线程中的小任务数*/
#define DELAY_TIME_LEVELS 10.0 /*小任务之间的最大时间间隔*/
using namespace std;
pthread_mutex_t mutex;//互斥锁声明
int status=1;//pthread_exit()函数返回值的演示
//多线程入口函数
void *thrd_func(void *arg) {//pthread_create()中的第四个参数作为入口函数的输入,可以传递变量但要注意类型
pthread_mutex_lock(&mutex);//加锁
int count;
int *temp=((int*)arg);
for (count = 0; count < REPEAT_NUMBER; count++) {
float delaytime=float((rand()%50)/40.0);
sleep(delaytime);
printf("\tThread %d-> Repeat: %d-> delay = %0.2f\n",*temp,count, delaytime);
}
printf("Thread %d of Repeat %d finished\n", *temp,count);
status+=((*temp)*100);
pthread_mutex_unlock(&mutex);//去锁
pthread_exit((void*)&status);//返回值可由pthread_join()函数来获取如下
}
int main(void) {
pthread_mutex_init(&mutex, NULL); //初始化互斥锁
pthread_t thread[THREAD_NUMBER];
int no, res;
for (no = 0; no < THREAD_NUMBER; no++) {
void* temp=&no;//将需要传递到入口函数中的变量强制类型转换
res = pthread_create(&thread[no], NULL, thrd_func, temp); //创建线程
if (res != 0) {
printf("Create thread %d failed\n", no);
exit(res);
}
}
void * thrd_ret; //初始一个变量接收pthread_join()的输出
for (no = 0; no < THREAD_NUMBER; no++) {
/* 等待线程结束 */
res = pthread_join(thread[no], &thrd_ret);//阻塞当前线程,第一个参数代表的线程。
if (!res) {
printf("Thread %d joined\n",(*(int*)thrd_ret));
}
else {
printf("Thread %d join failed %d\n", no);
}
}
pthread_mutex_destroy(&mutex); //释放锁资源。
return 0;
}
此为运行结果,不知道为什么有些地方的参数传递会出现问题,比如第一行中的Thread 2->应该为0才对,不知具体原因为何。
注意信号量的控制同样用来同步变量类似于互斥锁,相关函数如下。