1. 程式人生 > >執行緒建立 pthread_create 中自定義引數注意事項

執行緒建立 pthread_create 中自定義引數注意事項

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;
}

執行結果:

執行結果

可以看出,這種錯誤的傳遞方式並沒有得到應有的結果