無鎖的話就是要兩個線程不能同時通路一個變量。那麼這樣就幹脆用兩個任務連結清單,如果在讀隊列裡面的任務處理完成,同時寫隊列裡面又有任務了,就交換兩個隊列,交換任務隊列的動作由主線程來實作。基于這種思想代碼如下:
#include "public.h"
#include <list>
using namespace std;
list<int>* queueMain;
list<int>* queueThread;
int fdThread;
int fdMain;
int threadRunning = 1;
void* thread_func(void*ptr)
{
while(1)
{
char nouse_buf;
// 告訴主線程,我即将休眠
write(fdThread, &nouse_buf, 1);
// 阻塞調用
read(fdThread, &nouse_buf, 1);
// 開始工作
while(queueThread->size() > 0)
{
int task = queueThread->front();
queueThread->pop_front();
printf("task is %d\n", task);
}
}
}
int main()
{
// 定義兩個消息隊列用于交換
list<int> queue1;
list<int> queue2;
queueMain = &queue1;
queueThread = &queue2;
// 使用socketpair用于兩個線程的通信和同步
int fd[2];
socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
fdThread = fd[0];
fdMain = fd[1];
// 建立消費者線程
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
char nousebuf;
// 使用多路轉換器,同時檢測标準輸入和子線程通知檔案描述符
while(1)
{
fd_set set;
FD_ZERO(&set);
FD_SET(fdMain, &set);
FD_SET(STDIN_FILENO, &set);
int ret = select(fdMain+1, &set, NULL, NULL, NULL);
if(ret > 0)
{
// 如果檢測到标準輸入有資訊,讀取标準輸入
if(FD_ISSET(STDIN_FILENO, &set))
{
char buf[1024];
fgets(buf, sizeof(buf), stdin);
int task = atoi(buf);
queueMain->push_back(task);
if(threadRunning == 0)
{
write(fdMain, &nousebuf, 1);
threadRunning = 1;
}
}
// 如果子線程有通知,将子線程設定為休眠狀态
if(FD_ISSET(fdMain, &set))
{
// 說明子線程休眠了
// 首先把socket中的資料取出,如果不取出,那麼下一次的select調用不會阻塞
// 會通知主線程,fdMain有資料
read(fdMain, &nousebuf, 1);
if(queueMain->size() > 0)
{
// 交換兩個消息隊列
list<int>* tmp = queueThread;
queueThread = queueMain;
queueMain = tmp;
// 喚醒子線程
write(fdMain, &nousebuf, 1);
}
else
{
// 子線程休眠了
threadRunning = 0;
}
}
}
}
}