1. 程式人生 > >SDL2.0 多執行緒使用訊號量

SDL2.0 多執行緒使用訊號量

// SDL_Thread.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <windows.h>
#include "SDL/include/SDL.h"
#include "SDL/include/SDL_thread.h"
#pragma comment(lib, "sdl/lib/x86/SDL2.lib")

bool bQuit = false;//退出執行緒的型號
int nData = 0;//多執行緒操作的共享資料
SDL_sem *m_Lock;//訊號量
static int TestThread(void *ptr)
{
	int nThreadID = *(int*)ptr;
	while(1) {
		if (bQuit){
			break;
		}

		//Use this function to wait until a semaphore has a positive value and then decrements it.
		SDL_SemWait(m_Lock);

		printf("nThreadID: %d  資料:%d\n", nThreadID, nData++);//列印哪個執行緒

		//Use this function to atomically increment a semaphore's value and wake waiting threads.
		SDL_SemPost(m_Lock);
	}

	return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
	SDL_Init(SDL_INIT_EVERYTHING);

	//initial_value:the starting value of the semaphore
	m_Lock = SDL_CreateSemaphore(1);

	int m = 1;
	int n = 2;
	SDL_Thread *thread = SDL_CreateThread(TestThread, "", &m);
	SDL_Thread *thread1 = SDL_CreateThread(TestThread, "", &n);

	SDL_Delay(5000);
	bQuit = 1;//如果不置位,執行緒將一直列印
	int nStatus = 0;
	SDL_WaitThread(thread, &nStatus);

	SDL_Quit();
	return 0;
}