多线程通信和同步
使用互斥锁mutex
互斥锁mutex存在的问题
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
//Linux -lpthread
using namespace std;
static mutex mux;
void TestThread()
{
for(;;)
{
// 获取互斥量的锁,如果互斥量被其它线程锁定,当前线程阻塞.
// 直到获取到互斥量的锁,当前线程继续安全访问临界区共享资源.
// mux.lock();
// 使用 try_lock() 避免线程在尝试获取锁时被阻塞, 如果无法立即获取到互斥量的锁, 线程继续执行其他任务或等待一段时间再重试.
if (!mux.try_lock())
{
cout << "Thread ID: " << std::this_thread::get_id() << " was not able to acquire the lock\n";
cout << "." << flush;
this_thread::sleep_for(100ms);
continue;
}
cout << "==============================" << endl;
cout << "test 001" << endl;
cout << "test 002" << endl;
cout << "test 003" << endl;
cout << "==============================" << endl;
mux.unlock();
this_thread::sleep_for(1000ms);
}
}
int main(int argc, char* argv[])
{
// 创建 10 个线程进行
for (int i = 0; i < 10; i++)
{
thread th(TestThread);
th.detach();
}
getchar();
return 0;
}
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
//Linux -lpthread
using namespace std;
static mutex mux;
void TestThread()
{
for(;;)
{
//获取锁资源,如果没有则阻塞等待
//mux.lock();
if (!mux.try_lock())
{
cout << "." << flush;
this_thread::sleep_for(100ms);
continue;
}
cout << "==============================" << endl;
cout << "test 001" << endl;
cout << "test 002" << endl;
cout << "test 003" << endl;
cout << "==============================" << endl;
mux.unlock();
this_thread::sleep_for(1000ms);
}
}
void ThreadMainMux(int i)
{
for (;;)
{
mux.lock();
cout << i << "[in]" << endl;
this_thread::sleep_for(1000ms);
mux.unlock();
// 使 CPU 有机会调度到其它线程,防止当前线程释放 mutex 锁,又锁定 mutex 锁.
this_thread::sleep_for(1ms);
}
}
int main(int argc, char* argv[])
{
for (int i = 0; i < 3; i++)
{
thread th(ThreadMainMux, i + 1);
th.detach();
}
getchar();
for (int i = 0; i < 10; i++)
{
thread th(TestThread);
th.detach();
}
getchar();
return 0;
}