做网站赚钱难,拼多多网店代运营要多少费用,威海网站网站建设,百度竞价网站建设C多线程同步总结
关于C多线程同步
一、C11规范下的线程库
1、C11 线程库的基本用法#xff1a;创建线程、分离线程
#includeiostream
#includethread
#includewindows.h
using namespace std;
void threadProc()
{coutthis is in t…C多线程同步总结
关于C多线程同步
一、C11规范下的线程库
1、C11 线程库的基本用法创建线程、分离线程
#includeiostream
#includethread
#includewindows.h
using namespace std;
void threadProc()
{coutthis is in threadProc\n;coutthread1s id is this_thread::get_id()endl; //获取所属线程的id
}
void threadProc2(int num)
{coutthread num numendl;
}
void threadProc3()
{coutthis thread is detached\n;
}
void threadProc4()
{coutthis thread is detached and wont print in the same console.\n;
}
int main()
{thread a;//创建线程1定义线程后面再分配任务a thread(threadProc);thread b(threadProc2,5);//创建线程2 定义线程的时候分配任务参数类似于printf一样可以为多个a.join();b.join();//采用join主线程会阻塞等待子线程执行完毕thread c(threadProc3);c.detach();//采用detach主线程不会等这个线程开启早还能输出到主线程的控制台coutmain thread exitendl;thread d(threadProc4);d.detach();//
}
运行结果 2、基本的互斥锁
上述运行输出语句显然没有顺序执行为了达到一行一行输出的效果可以使用最基本的互斥锁。
#includeiostream
#includethread
#includemutex
using namespace std;
mutex mu;//互斥锁
void test1()
{for(int i0;i5;i){
// mu.lock();//锁住 couttest1 i iendl;
// mu.unlock();//释放 }
}
void test2()
{for(int j0;j5;j){
// mu.lock();couttest2 j jendl;
// mu.unlock();}
}
int main()
{thread a(test1);thread b(test2);a.join();b.join();coutmain thread finish.endl;
}
运行结果 不加锁的话输出就会混乱。
这里打开4行注释重新运行。
运行结果 可以简单理解为test1获得锁以后test2调用lock()就会阻塞执行直到test1()调用unlock()释放锁。
3、lock_guard
#include iostream
#include thread
#include mutexmutex mu;//互斥锁
/*
lock_guardmutex locka(mu);
作用范围为从这一行开始到那一次循环结束还不用自己手动解锁。
*/
void test3()
{for(int i0;i5;i){std::lock_guardstd::mutex locka(mu); std::cout test3 i i std::endl;}
}
void test4()
{for(int j0;j5;j){std::lock_guardstd::mutex lock(mu);std::cout test4 j j std::endl;}
}
int main()
{std::thread a(test3);std::thread b(test4);a.join();b.join();std::coutmain thread finish.std::endl;
}
运行结果 4、unique_lock
#includeiostream
#includethread
#includemutex
using namespace std;
mutex mu;//互斥锁
void test5()
{for(int i0;i5;i){unique_lockmutex locka(mu,defer_lock); couttest5 i iendl;locka.lock();coutthis is lock1endl;}
}
void test6()
{for(int j0;j5;j){unique_lockmutex locka(mu); couttest6 j jendl;locka.unlock();locka.lock();coutthis is lock2endl;}
}
int main()
{thread a(test5);thread b(test6);a.join();b.join();coutmain thread finish.endl;
}
运行结果 5、condition_variable
#includeiostream
#includethread
#includemutex
#includecondition_variableusing namespace std;mutex mu;
condition_variable cv;
bool print false;
void test7()
{for(int i0;i5;i){unique_lockmutex l(mu);couttest7 i iendl;cv.notify_one();print true;}
}
void test8()
{for(int j0;j5;j){unique_lockmutex l(mu);if(!print){cv.wait(l);}couttest8 j jendl;print false;}
}
int main()
{thread a(test7);thread b(test8);a.join();b.join();
}
运行结果 二、Win32 API 实现线程同步
1、临界区 #include iostream
#include thread
#include windows.husing namespace std;CRITICAL_SECTION section;//临界区变量void test01()
{for(int i0;i5;i){EnterCriticalSection(section);//类似于 mutex.lock() coutthis is test01 i iendl;Sleep(1);LeaveCriticalSection(section);//类似于 mutex.unlock() }
}
void test02()
{for(int j0;j5;j){EnterCriticalSection(section);coutthis is test02 j jendl;Sleep(1);LeaveCriticalSection(section);}
}
int main()
{InitializeCriticalSection(section);//初始化临界区对象thread a(test01);thread b(test02);a.join();b.join();DeleteCriticalSection(section);//用完了就删除临界区
}
运行结果 效果类似于mutex只是都要在执行完循环进行解锁的操作。
2、互斥锁
#includeiostream
#includethread
#includewindows.h
using namespace std;
HANDLE hmutex;
void test03()
{for(int i0;i5;i){WaitForSingleObject(hmutex,INFINITE);//类似于mutex.lock() 阻塞等待多少时间 couttest03 i iendl;ReleaseMutex(hmutex);//类似于mutex.unlock() 释放互斥锁 }
}
void test04()
{for(int j0;j5;j){WaitForSingleObject(hmutex,INFINITE);couttest04 j jendl;ReleaseMutex(hmutex);}
}
int main()
{hmutex CreateMutex(NULL,FALSE,mutex);//创建一个互斥锁 thread a(test03);thread b(test04);a.join();b.join();CloseHandle(hmutex);//释放句柄
}
运行结果 3、事件
#includeiostream
#includethread
#includewindows.husing namespace std;HANDLE hevent;
void test05()
{for(int i0;i5;i){WaitForSingleObject(hevent,INFINITE);//类似于mutex.lock() 阻塞等待多少时间 couttest05 i iendl;SetEvent(hevent);//类似于mutex.unlock() 释放互斥锁 }
}
void test06()
{for(int j0;j5;j){WaitForSingleObject(hevent,INFINITE);couttest06 j jendl;SetEvent(hevent);}
}
int main()
{hevent CreateEvent(NULL,FALSE,TRUE,event);//创建一个事件 thread a(test05);thread b(test06);a.join();b.join();CloseHandle(hevent);//释放句柄
}
运行结果 4、信号量
#include iostream
#include thread
#include windows.husing namespace std;HANDLE sem;
void test07()
{for(int i0;i5;i){WaitForSingleObject(sem,INFINITE);//类似于mutex.lock() 阻塞等待多少时间 couttest07 i iendl;ReleaseSemaphore(sem,1,NULL);//类似于mutex.unlock() 释放互斥锁 }
}
void test08()
{for(int j0;j5;j){WaitForSingleObject(sem,INFINITE);couttest08 j jendl;ReleaseSemaphore(sem,1,NULL);}
}
int main()
{sem CreateSemaphore(NULL,1,2,semaphore);thread a(test07);thread b(test08);a.join();b.join();CloseHandle(sem);//释放句柄
}
运行结果 #include iostream
#include fstream
#include random
#include ctime#include windows.h
//#include time.h
#include stdio.h
#include math.h
#include bitset#include thread
#include mutex
#include condition_variable#define NAME_LINE 40
void* g_hMutex2 NULL; //使用适当的初始化方式
//定义线程函数传入参数的结构体
typedef struct __TICKET
{int nCount;char strTicketName[NAME_LINE];__TICKET() : nCount(0){memset(strTicketName, 0, NAME_LINE * sizeof(char));}
}TICKET;typedef struct __THD_DATA
{TICKET* pTicket;char strThreadName[NAME_LINE];__THD_DATA() : pTicket(NULL){memset(strThreadName, 0, NAME_LINE * sizeof(char));}
}THD_DATA;//基本类型数据转换成字符串
templateclass T
std::string convertToString(const T val)
{std::string s;std::strstream ss;ss val;ss s;return s;
}
//售票程序
DWORD WINAPI SaleTicket(LPVOID lpParameter);//售票系统
void Test2();// 一个mutex变量控制同一个资源因此会先打印完*再打印$
// 两个mutex变量则可能出现交替打印因为不是修改统一资源
std::mutex mtx; // mutex for critical section
void print_block(int n, char c)
{mtx.lock();for (int i 0; in; i){std::cout c;}std::cout \n;mtx.unlock();
}
void thread_1()
{std::cout 子线程1 std::endl;
}
void thread_2(int x)
{std::cout x: x std::endl;std::cout 子线程2 std::endl;
}
int f_multi_thread()
{std::thread first(thread_1); // 开启线程调用thread_1()std::thread second(thread_2, 100); // 开启线程调用thread_2(100)//std::thread third(thread_2,3);//开启第3个线程共享thread_2函数。std::cout 主线程\n;first.join(); //join()等待线程结束并清理资源(会阻塞) second.join();std::cout 子线程结束.\n;//必须join完成//std::thread th1(print_block, 50, *);//线程1打印*//std::thread th2(print_block, 50, $);//线程2打印$//th1.join();//th2.join();return 0;
}void threadProc()
{std::cout this is in threadProc\n;std::cout thread1s id is std::this_thread::get_id() std::endl; //获取所属线程的id
}
void threadProc2(int num)
{std::cout thread num num std::endl;
}
void threadProc3()
{std::cout this thread is detached\n;
}
void threadProc4()
{std::cout this thread is detached and wont print in the same console.\n;
}
std::mutex mu;//互斥锁
void test1()
{for (int i 0; i 5; i){mu.lock();//锁住 std::cout test1 i i std::endl;mu.unlock();//释放 }
}
void test2()
{for (int j 0; j 5; j){mu.lock();std::cout test2 j j std::endl;mu.unlock();}
}
/*
lock_guardmutex locka(mu);
作用范围为从这一行开始到那一次循环结束还不用自己手动解锁。
*/
void test3()
{for (int i 0; i 5; i){std::lock_guardstd::mutex locka(mu);std::cout test3 i i std::endl;}
}
void test4()
{for (int j 0; j 5; j){std::lock_guardstd::mutex lock(mu);std::cout test4 j j std::endl;}
}
void test5()
{for (int i 0; i 5; i){std::unique_lockstd::mutex locka(mu, std::defer_lock);std::cout test5 i i std::endl;locka.lock();std::cout this is lock1 std::endl;}
}
void test6()
{for (int j 0; j 5; j){std::unique_lockstd::mutex locka(mu);std::cout test6 j j std::endl;locka.unlock();locka.lock();std::cout this is lock2 std::endl;}
}
std::condition_variable cv;
bool print false;
void test7()
{for (int i 0; i 5; i){std::unique_lockstd::mutex l(mu);std::cout test7 i i std::endl;cv.notify_one();print true;}
}
void test8()
{for (int j 0; j 5; j){std::unique_lockstd::mutex l(mu);if (!print){cv.wait(l);}std::cout test8 j j std::endl;print false;}
}CRITICAL_SECTION section;//临界区变量
void test01()
{for (int i 0; i 5; i){EnterCriticalSection(section);//类似于 mutex.lock() std::cout this is test01 i i std::endl;Sleep(1);LeaveCriticalSection(section);//类似于 mutex.unlock() }
}
void test02()
{for (int j 0; j 5; j){EnterCriticalSection(section);std::cout this is test02 j j std::endl;Sleep(1);LeaveCriticalSection(section);}
}
HANDLE hmutex;
void test03()
{for (int i 0; i 5; i){WaitForSingleObject(hmutex, INFINITE);//类似于mutex.lock() 阻塞等待多少时间 std::cout test03 i i std::endl;ReleaseMutex(hmutex);//类似于mutex.unlock() 释放互斥锁 }
}
void test04()
{for (int j 0; j 5; j){WaitForSingleObject(hmutex, INFINITE);std::cout test04 j j std::endl;ReleaseMutex(hmutex);}
}
HANDLE hevent;
void test05()
{for (int i 0; i 5; i){WaitForSingleObject(hevent, INFINITE);//类似于mutex.lock() 阻塞等待多少时间 std::cout test05 i i std::endl;SetEvent(hevent);//类似于mutex.unlock() 释放互斥锁 }
}
void test06()
{for (int j 0; j 5; j){WaitForSingleObject(hevent, INFINITE);std::cout test06 j j std::endl;SetEvent(hevent);}
}
HANDLE sem;
void test07()
{for (int i 0; i 5; i){WaitForSingleObject(sem, INFINITE);//类似于mutex.lock() 阻塞等待多少时间 std::cout test07 i i std::endl;ReleaseSemaphore(sem, 1, NULL);//类似于mutex.unlock() 释放互斥锁 }
}
void test08()
{for (int j 0; j 5; j){WaitForSingleObject(sem, INFINITE);std::cout test08 j j std::endl;ReleaseSemaphore(sem, 1, NULL);}
}int main(int argc, char const* argv[])
{int i 0; int rtn 0;int ret 0;char buff[100];char *tmp int2hex(82);//read_csv2();//ok//float num 0.3;//int result ceil(num);//printf(向上取整后的结果是%d\n, result);--------------多线程-----START------------------------//f_multi_thread();//f_multiThread();//【Demo1】创建一个最简单的线程//f_multiThread2();//【Demo2】在线程函数中传入参数//f_multiThread3();//【Demo3】线程同步//售票系统 ////Test2();//【Demo4】模拟火车售票系统 C11 线程库 START //std::thread a;//创建线程1定义线程后面再分配任务//a std::thread(threadProc);//std::thread b(threadProc2, 5);//创建线程2 定义线程的时候分配任务参数类似于printf一样可以为多个//a.join();//b.join();//采用join主线程会阻塞等待子线程执行完毕//std::thread c(threadProc3);//c.detach();//采用detach主线程不会等这个线程开启早还能输出到主线程的控制台//std::cout main thread exit std::endl;//std::thread d(threadProc4);//d.detach();////std::thread a(test1);//std::thread b(test2);//a.join();//b.join();//std::cout main thread finish. std::endl;//std::thread a(test3);//std::thread b(test4);//a.join();//b.join();//std::cout main thread finish. std::endl;//std::thread a(test5);//std::thread b(test6);//a.join();//b.join();//std::thread a(test7);//std::thread b(test8);//a.join();//b.join(); C11 线程库 END W32API实现线程同步 START //InitializeCriticalSection(section);//初始化临界区对象//std::thread a(test01);//std::thread b(test02);//a.join();//b.join();//DeleteCriticalSection(section);//用完了就删除临界区 //hmutex CreateMutex(NULL, FALSE, mutex);//创建一个互斥锁 //std::thread a(test03);//std::thread b(test04);//a.join();//b.join();//CloseHandle(hmutex);//释放句柄 //hevent CreateEvent(NULL, FALSE, TRUE, event);//创建一个事件 //std::thread a(test05);//std::thread b(test06);//a.join();//b.join();//CloseHandle(hevent);//释放句柄 sem CreateSemaphore(NULL, 1, 2, semaphore);std::thread a(test07);std::thread b(test08);a.join();b.join();CloseHandle(sem);//释放句柄 W32API实现线程同步 END --------------多线程-----END--------------------------VS 与 Matlab 混合编程//rtn f_VS_Matlab();system(pause);return 0;
}//售票程序
DWORD WINAPI SaleTicket(LPVOID lpParameter)
{THD_DATA* pThreadData (THD_DATA*)lpParameter;TICKET* pSaleData pThreadData-pTicket;while (pSaleData-nCount 0){//请求获得一个互斥量锁WaitForSingleObject(g_hMutex2, INFINITE);if (pSaleData-nCount 0){std::cout pThreadData-strThreadName 出售第 pSaleData-nCount-- 的票,;if (pSaleData-nCount 0) {std::cout 出票成功!剩余 pSaleData-nCount 张票. std::endl;}else {std::cout 出票失败该票已售完。 std::endl;}}Sleep(10);//释放互斥量锁ReleaseMutex(g_hMutex2);}return 0L;
}
//售票系统
void Test2()
{//创建一个互斥量g_hMutex2 CreateMutex(NULL, FALSE, NULL);//初始化火车票TICKET ticket;ticket.nCount 100;strcpy(ticket.strTicketName, 北京--赣州);const int THREAD_NUMM 2;//8;//THD_DATA threadSale[THREAD_NUMM];HANDLE hThread[THREAD_NUMM];for (int i 0; i THREAD_NUMM; i){threadSale[i].pTicket ticket;std::string strThreadName convertToString(i);strThreadName 窗口 strThreadName;strcpy(threadSale[i].strThreadName, strThreadName.c_str());//创建线程hThread[i] CreateThread(NULL, NULL, SaleTicket, threadSale[i], 0, NULL);//请求获得一个互斥量锁WaitForSingleObject(g_hMutex2, INFINITE);std::cout threadSale[i].strThreadName 开始出售 threadSale[i].pTicket-strTicketName 的票... std::endl;//释放互斥量锁ReleaseMutex(g_hMutex2);//关闭线程CloseHandle(hThread[i]);}system(pause);
}参考
【Linux】多线程同步的四种方式 - 西*风 - 博客园 (cnblogs.com)
一文搞定c多线程同步机制_c多线程同步等待-CSDN博客
C多线程同步总结 - 念秋 - 博客园 (cnblogs.com)
Linux 下多线程C语言 | 大眼睛男孩儿 (zhangxiaoya.github.io)
读写锁 - 张飘扬 - 博客园 (cnblogs.com)
Linux C多线程同步的四种方式非常详细-CSDN博客