1. 函數原型
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
本文主要討論最後一個參數,同時傳遞多個的問題
(如果只傳遞一個 int char 等長度小於指針的數據類型,可以直接傳,然後在線程內把 (void *) 強制轉換)
2. 錯誤示例 是在一本書上看到的,也是寫本文的初衷
錯誤原因: fds_for_new_worker 是局部變量,線程創建異步的,pthread_create 後, else if 也結束了,該變量的生命週期結束,worker 線程訪問到的將是野指針,容易造成數據訪問錯誤或更嚴重的內存錯誤。
3. 正確傳遞方法
A. 使用全局變量(視情況使用)
變量的作用域不會消失,但要注意多線程變量同步問題
B. 動態分配變量空間(推薦)
在 pthread_create 前 malloc() 申請空間,在線程內使用完後 free()
附:錯誤代碼驗證
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
struct data_st
{
int a;
int b;
};
static void *start_routine(void *user)
{
// sleep(1);
struct data_st *data = (struct data_st *)user;
printf("in thread, data->a = %d, data->b = %d\n", data->a, data->b);
pthread_detach(pthread_self());
return NULL;
}
int main(void)
{
int i;
int ret;
pthread_t pt;
for (i = 0; i < 5; ++i)
{
struct data_st data;
data.a = i;
data.b = i * 2;
ret = pthread_create(&pt, NULL, start_routine, &data);
if (0 != ret)
{
printf("%s(): Thread creation failed\n", __FUNCTION__);
exit(EXIT_FAILURE);
}
}
pause();
return 0;
}
運行結果:
可以看出,這種錯誤的傳遞方式並沒有得到應有的結果