mutex,thread

//#include <stdio.h>
//#include <stdlib.h>
//#include <unistd.h>
#include <windows.h>
//#include <pthread.h>
#include <mutex>
#include <thread>
#include <string.h>

using namespace std;
char* buf[5]; //字符指針數組  全局變量
int pos; //用於指定上面數組的下標

//1.定義互斥量 
//pthread_mutex_t mutex;  // linux  
mutex mtx;	// C++11
HANDLE g_hMutex = INVALID_HANDLE_VALUE;  // Win
void *task(void *p)
{
	//3.使用互斥量進行加鎖
	//pthread_mutex_lock(&mutex);  // linux  
	//mtx.lock();	// C++11
	WaitForSingleObject(g_hMutex, INFINITE);//等待互斥量 Win

	buf[pos] = (char *)p;


	printf("task %d\r\n", pos);
	//sleep(1);   // linux  
	Sleep(500);	  // Win
	
	pos++;

	//4.使用互斥量進行解鎖
	//pthread_mutex_unlock(&mutex); // linux  
	//mtx.unlock();	// C++11
	ReleaseMutex(g_hMutex);//釋放互斥量  // Win

	return 0;
}

int main(void)
{
	//2.初始化互斥量, 默認屬性
	//pthread_mutex_init(&mutex, NULL);  // linux  
	g_hMutex = CreateMutex(nullptr, false, nullptr);   // Win

	//1.啓動一個線程 向數組中存儲內容
	//pthread_t tid, tid2;  // linux  
	//pthread_create(&tid, NULL, task, (void *)"woainia!"); // linux  
	//pthread_create(&tid2, NULL, task, (void *)"how"); // linux  

    // CreateThread(nullptr,0...)  // Win
	thread  th1(task, (void *)"woainia!");  // C++
	thread  th2(task, (void *)"how");		// C++

	//2.主線程進程等待,而且打印最終的結果
	//pthread_join(tid, NULL);   // linux  
	//pthread_join(tid2, NULL);  // linux  
	
	th2.join();		// C++
	th1.join();		// C++

	//5.銷燬互斥量
	//pthread_mutex_destroy(&mutex);  // linux  
	CloseHandle(g_hMutex);	// Win

	Sleep(5000);
	int i = 0;
	printf("字符指針數組中的內容是:pos:%d \r\n", pos);
	for (i = 0; i < pos; ++i)
	{
		printf("%d : %s \n", i, buf[i]);
	}
	printf("\n");

	system("pause");
	return 0;
}

相關文章
相關標籤/搜索