1. 程式人生 > 實用技巧 >C++ 執行緒傳遞多個引數

C++ 執行緒傳遞多個引數

使用多執行緒處理共享資料 有些情況下需要傳遞多個引數

定義一個結構體:將這個結構體指標,作為void *形參的實際引數傳遞.

函式中需要定義一個mypara型別的結構指標來引用這個引數



structthread_param
{
void*pthis=NULL;
inti=-1;
};

int main()
{
   vector<pthread_t> thread_ids(1);
    for (size_t i = 0; i < 1; ++i)
    {
        struct thread_param tp;
        tp.pthis = (void
*)this; tp.i = i; if (0 != pthread_create(&thread_ids[i], NULL, &do_check_thread_func, (void *)&tp)) { WRITE_LOG(LOG_ERROR, "pthread_create failed in 10018877"); return -1; } WRITE_LOG(LOG_DEBUG, "do_check_thread_func create thread successfully, tid: %u
", thread_ids[i]); } for (size_t i = 0; i < 1; ++i) { pthread_join(thread_ids[i], NULL); } return 0; } void* do_check_thread_func(void *data) { thread_param *tt; tt = (struct thread_param*)data; void *param = tt->pthis; int i = tt->i; myclass
* pThis = (myclass*)param; WRITE_LOG(LOG_DEBUG, "10018877 do_check_thread_func create thread successfully, i:%d", i); }