[ create a new paste ] login | about

Link: http://codepad.org/B3Yid7rc    [ raw code | output | fork ]

C++, pasted on Jul 23:
#include <Windows.h>
#include "stdio.h"
#include "stdlib.h"
#include <process.h>

class TestWrapperMultThreadToClass
{
public:
	TestWrapperMultThreadToClass(int ThreadNum)
	{
		_ThreadNum = ThreadNum; // 要開幾個執行緒
		tb = new ThreadBlockParam[_ThreadNum]; // 宣告與執行緒數相當的參數陣列,這樣才可以一個執行緒一個相對應的參數
		for (int i = 0; i < _ThreadNum; i++) // 初始化,讓每個參數的IsIdle都是true,代表該執行緒目前空閒
			(tb + i)->IsIdle = true;

		TestTimes = 16; 
	}

	~TestWrapperMultThreadToClass()
	{

	}

	bool TestMultThreadSendParam()
	{
		int ThreadIndex = 0;
		unsigned int ThreadId_For_Beginthreadex_Function = 0;
		for (int i = 0; i < TestTimes; i++)
		{
			while ((tb + ThreadIndex)->IsIdle == false) // 看現在哪個執行緒是空的
			{
				if (ThreadIndex < _ThreadNum - 1)
					ThreadIndex++;
				else
					ThreadIndex = 0;
			}

			ThreadId_For_Beginthreadex_Function = static_cast<unsigned int>(ThreadIndex);
			nowThread = ThreadIndex; // 記錄現在的參數要給哪個執行緒
                        // 塞參數
			(tb + i)->ThreadIndex = ThreadIndex;
			(tb + i)->InIterativeTimes = i;
			(tb + i)->IsIdle = false;
			_beginthreadex(NULL, 0, FunctionCalledByThread, this, 0, &ThreadId_For_Beginthreadex_Function);
		}
		IsAllThreadComeBack(tb, _ThreadNum); // 檢查是否每個執行緒都回來了

		return true;
	}

private:
	int _ThreadNum, TestTimes;
	int nowThread;
	typedef struct _ThreadBlockParam
	{
		int ThreadIndex;
		int InIterativeTimes;
		bool IsIdle;
	}ThreadBlockParam;
	ThreadBlockParam *tb;

	static unsigned int __stdcall FunctionCalledByThread(void *ptr_this)
	{
		TestWrapperMultThreadToClass *_this = static_cast<TestWrapperMultThreadToClass*>(ptr_this);
		_this->Test();
		return 1;
	}

	void Test()
	{
		ThreadBlockParam *temp = tb + nowThread; // 取得與現下這個執行緒相對應的參數結構
		int ThreadId = GetCurrentThreadId();
		char Msg[200];
		sprintf_s(Msg, 200, "In %d-th thread, thread id = %d!\n", temp->ThreadIndex, ThreadId);
		printf(Msg);
		Sleep(5000); // 停5秒,不要讓執行緒太快回去,不然没辦法知道,我是不是成功分配到每個執行緒
		tb->IsIdle = true;
	}

	bool IsAllThreadComeBack(ThreadBlockParam *tb, int ThreadNum)
	{
		int count = 0;

		while (count < ThreadNum)
		{
			if ((tb + count)->IsIdle == true)
				count++;
		}
		return true;
	}

};

void main()
{
	TestWrapperMultThreadToClass *Test = new TestWrapperMultThreadToClass(8);
	Test->TestMultThreadSendParam();

	printf("Multiple thread wrapper to class testing is finishing!\n");

	system("pause");
}


Output:
1
2
3
4
Line 20: error: Windows.h: No such file or directory
Line 20: error: process.h: No such file or directory
Line 62: error: expected ';' before 'FunctionCalledByThread'
compilation terminated due to -Wfatal-errors.


Create a new paste based on this one


Comments: