C++ 線程傳遞多個參數


使用多線程處理共享數據  有些情況下需要傳遞多個參數

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

函數中需要定義一個mypara類型的結構指針來引用這個參數

 
         
struct thread_param
{
  void * pthis = NULL;
  int i = -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); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM