1. 互斥
1.1 为什么需要互斥
多线程抢票模型演示了并发访问共享数据的问题。
#include<iostream>
#include<unistd.h>
#include<pthread.h>
#include<string>
#include<vector>
using namespace std;
#define NUM 4
int ticket = 100; // 用多线程,模拟一轮抢票
class ThreadData {
public:
ThreadData(int number){ _thread_name = "thread-" + to_string(number); }
public:
string _thread_name;
};
void* GetTicket(void* args) {
ThreadData* td = static_cast<ThreadData*>(args);
const char* name = td->_thread_name.c_str();
while(true) {
if(ticket > 0){
usleep(5000);
printf("i am %s, get a ticket:%d\n", name, ticket);
ticket--;
} else break;
}
(, name);
;
}
{
vector<> tids;
vector<ThreadData*> thread_datas;
( i=; i<NUM; i++) {
tid;
ThreadData* td = (i);
thread_datas.(td);
(&tid, , GetTicket, thread_datas[i]);
tids.(tid);
}
( &e : tids) {
(e, );
}
( &e : thread_datas) {
e;
}
;
}


