线程,Mutex简单用法

来源:互联网 发布:java模拟器安卓版5.1 编辑:程序博客网 时间:2024/06/02 15:53

1.很挫的做法,实现线程按顺序干活

define a controller obj

class Controler{public:Controler(): order_(0){mutex_ = CreateMutex(NULL, FALSE, NULL);}Controler(const Controler& assign_obj){this->mutex_ = assign_obj.mutex_;this->order_ = assign_obj.order_;}~Controler(){CloseHandle(mutex_);}Controler& operator = (const Controler& assign_obj){this->mutex_ = assign_obj.mutex_;this->order_ = assign_obj.order_;return *this;}public:void GetCurrentOrder(int& res){DWORD d = WaitForSingleObject(mutex_, INFINITE);res = order_;ReleaseMutex(mutex_);}void SetCurrentOrder(int new_order){DWORD d = WaitForSingleObject(mutex_, INFINITE);order_ = new_order;ReleaseMutex(mutex_);}private:HANDLEmutex_;intorder_;};typedef struct target{int target_id;Controler*  controler;} tagMsg;


define thread function:

DWORD WINAPI ThreadProc(LPVOID lpParam){tagMsg* msg = (tagMsg*)lpParam;Controler* controler = msg->controler;int res = -1;controler->GetCurrentOrder(res);printf("----->>> raining data , current order is %d , target id is %d <<<-------\n", res, msg->target_id);while (true){controler->GetCurrentOrder(res);if (res == msg->target_id){break;}Sleep(30);}int new_order = res+1;printf("-----*** congratulations young man , the new order is %d ***-------\n", new_order);controler->SetCurrentOrder(new_order);return 0;}
test code:

const int max_thread = 30;LPDWORD thread_id[max_thread];HANDLE handle[max_thread];tagMsg para[max_thread];std::shared_ptr<Controler> wangyl(new Controler());for (int i = 0; i < max_thread; ++i){thread_id[i] = nullptr;para[i].target_id = i;para[i].controler = wangyl.get();handle[i] = CreateThread(NULL, 0, ThreadProc, (LPVOID)¶[i], 0, thread_id[i]);}WaitForMultipleObjects(max_thread, handle, TRUE, INFINITE);for (int i = 0; i < max_thread; ++i){CloseHandle(handle[i]);}
result:





0 0
原创粉丝点击