// windows平台
#include <windows.h>
#include <iostream.h>
DWORD WINAPI Fun1(LPVOID lpParameter);
DWORD WINAPI Fun2(LPVOID lpParameter);
int index = 0;
int tickets = 100;
HANDLE hMutex;
void main(){
HANDLE hThread1;
HANDLE hThread2;
// 创建线程
hThread1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, Fun2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
// 创建互斥对象
hMutext = CreateMutex(NULL, FALSE, NULL);
Sleep(4000);
}
DWORD WINAPI Fun1(LPVOID lpparameter){
while(TRUE){
WaitForSingleObject(hMutext, INFINITE);
if(tickets > 0){
Sleep(1);
std::cout << "thread1 sell ticket:"<< tickets--<<std::endl;
}else{
break;
}
ReleaseMutex(hMutex);
}
return 0;
}
DWORD WINAPI Fun2(LPVOID lpParamter){
while(TRUE){
// 注:互斥对象谁拥有,谁释放。
WaitForSingleObject(hMutex, INFINITE);
if(tickets > 0){
Sleep(1);
std::cout << "thread2 sell ticket:"<< tickets--<<std::endl;
}else{
break;
}
ReleaseMutex(hMutext);
}
return 0;
}
``
windows平台mutex知识点
1. CreateMutex
创建或者打开一个命令的或者匿名的互斥对象。
互斥对象包含一个使用数量,一个线程ID和一个计数器。
其中ID用于标识系统中的那个线程当前拥有互斥对象,
计数器用于指明该线程拥有互斥对象的次数。
2. WaitForSingleObject
获取对象的所有权
2.1 原型声明
DWORD WaitForSingleObject(HANDLE hHandle, DWORD dwMilliseconds);
2.2 返回值
如果函数调用成功,那么WaitForSingleObject函数的返回值将表明引起该返回的事件。
| 返回值 | 说明
| WAIT_OBJECT_O | 所请求得对象是有信号状态
| WAIT_TIMEOUT | 指定的时间间隔已过,并且请求的对象是无信号状态
| WAIT_ABANDONED | 所请求的对象是一个互斥对象,并且先前拥有该对对象
的线程在终止前没有释放该对象,这时,该对象的所有权授予当前调用线程,并且该互斥对象被设置为无信号状态
```c++
// Linux平台
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mutex_x = PTHREAD_MUTEX_INITIALIZER;
int total_ticket_num = 20;
void * sell_ticket(void * arg){
for(int i = 0; i < 20; i++){
pthread_mutex_lock(&mutex_x);
if(total_ticket_num > 0){
sleep(1);
printf("sell the %dth ticket\n", 20-total_ticket_num + 1);
total_ticket_num--;
}
pthread_mutex_unlock(&mutex_x);
}
return 0;
}
int main(){
int iRet;
pthread_t tids[4];
int i = 0;
for(i = 0;i < 4; i++){
int iRet = pthread_create(%tids[i], NULL, &sell_ticket, NULL);
if(iRet){
return iRet;
}
}
sleep(30);
void * retval;
for(i = 0;i < 4; i++){
iRet = pthread_join(tids[i], &retval);
if(iRet){
printf("tid=%d join error, iRet = %d\n", tids[i], iRet);
return iRet;
}
}
return 0;
}