基本使用
#include <string>#include <pthread.h>#include <unistd.h>#include "testThread.h"#include "mylog.h"using namespace std;//自定义一个函数,异步任务使用void *customPThreadMethod(void *value) {int tempValue = *static_cast<int *>(value); //接收从外部传入的值LOG("accept value from out method is %d", tempValue);for (int i = 0; i < 10; ++i) {sleep(1);LOG("customPThreadMethod:%d", i + 1);}return 0;}void main_testThread() {//线程基本使用// int pthread_create(pthread_t *__pthread_ptr, pthread_attr_t const *__attr,// void *(*__start_routine)(void *), void *);pthread_t pThreadID; //函数指针int value = 1000;pthread_create(&pThreadID, 0, customPThreadMethod, &value);pthread_join(pThreadID, 0); //会等待线程执行完毕之后,才会执行后面的代码LOG("after thread");}
使用升级
分离线程和非分离线程 非分离线程,要等到耗时任务执行全部完成以后,先执行异步任务,才会执行join后面关联的代码逻辑
分离线程,各玩各的,老死不相往来,所以就造成了,不管异步任务是否执行完毕,该结束就结束
#include <string>#include <pthread.h>#include <unistd.h>#include "testThread.h"#include "mylog.h"using namespace std;//自定义一个函数,异步任务使用void *customPThreadMethod(void *value) {int tempValue = *static_cast<int *>(value);// int tempValue = *((int *)value);LOG("accept value from out method is %d", tempValue);for (int i = 0; i < 10; ++i) {sleep(1);LOG("customPThreadMethod:%d", i + 1);}return 0; //必须返回一个值,不然程序会闪退}void main_testThread() {pthread_t pThreadID; //线程ID,允许有野指针pthread_attr_t pThreadAttr; //线程属性,不允许有野指针 有坑//初始化:线程属性pthread_attr_init(&pThreadAttr);//开启分离线程,pthread_join就失效了// pthread_attr_setdetachstate(&pThreadAttr, PTHREAD_CREATE_DETACHED);//开启非分离线程和pthread_join关联起来了pthread_attr_setdetachstate(&pThreadAttr, PTHREAD_CREATE_JOINABLE);int value = 1000;pthread_create(&pThreadID, &pThreadAttr, customPThreadMethod, &value);//会等待线程执行完毕之后,才会执行后面的代码pthread_join(pThreadID, 0);//线程属性,进行回收pthread_attr_destroy(&pThreadAttr);LOG("after thread");}
线程安全互斥锁
#include <string>#include <pthread.h>#include <unistd.h>#include <queue>#include "mylog.h"#include "testUpdateThread.h"using namespace std;queue<int> saveAllData;pthread_mutex_t mutex; //互斥锁//自定义一个函数,异步任务使用void *customPThreadUpdateMethod(void *value) {//线程加锁pthread_mutex_lock(&mutex);int tempValue = *static_cast<int *>(value);// int tempValue = *((int *)value);LOG("accept value from out method is %d", tempValue);if (!saveAllData.empty()) {LOG("获取队列的数据:%d\n", saveAllData.front());saveAllData.pop(); // 把数据弹出去,删除的意思} else {LOG("队列中没有数据了\n");}// 解除锁定,是为了让其他多线程,可以进来的操作,这就是解锁的目的pthread_mutex_unlock(&mutex);return 0; //必须返回一个值,不然程序会闪退}void main_testUpdateThread(){pthread_mutex_init(&mutex, nullptr);for (int i = 1000; i < 10010; ++i) {saveAllData.push(i);}pthread_t pThreadID[10];for (int i = 0; i < 10; ++i) {pthread_create(&pThreadID[i], 0, customPThreadUpdateMethod, &i);pthread_join(pThreadID[i], 0);}LOG("函数已经执行到了这里");//回收互斥锁pthread_mutex_destroy(&mutex);}
