我發現了幾個使用動態記憶體分配方法將整數作為最后一個引數傳遞的代碼,如下例所示:
void *foo(void *i) {
int a = *((int *) i);
free(i);
}
int main() {
pthread_t thread;
for ( int i = 0; i < 10; 1 ) {
int *arg = malloc(sizeof(*arg));
if ( arg == NULL ) {
fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
exit(EXIT_FAILURE);
}
*arg = i;
pthread_create(&thread, 0, foo, arg);
}
/* Wait for threads, etc */
return 0;
}
否則,我找到了使用陣列方法的學術示例,例如傳遞結構的示例:
//Runnable example
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct my_Struct{
int index;
int value;
};
void* my_Func(void *received_struct){
struct my_Struct *struct_ptr = (struct my_Struct*) received_struct;
printf("index: %d | value: %d \n", struct_ptr->index, struct_ptr->value);
//Now use 'struct_ptr->index', 'struct_ptr->value' as you wish
}
int main(){
struct my_Struct mystruct_1[5];
printf("\nEnter 5 numbers:\n");
for (int i=0; i<5; i ){
scanf("%d", &mystruct_1[i].value);
mystruct_1[i].index = i;
}
pthread_t tid[5];
for(int i=0; i<5; i ){
pthread_create(&(tid[i]), NULL, my_Func, &mystruct_1[i]);
}
for (int i=0; i<5; i ){
pthread_join(tid[i], NULL);
}
}
//To run: gcc [C FILE].c -lpthread -lrt
// ./a.out
//Grepper Profile: https://www.codegrepper.com/app/profile.php?id=9192
動態記憶體分配方法的優勢是什么?
更新:我在基于 gcc 的 IBM i 檔案中發現他們使用記憶體分配
uj5u.com熱心網友回復:
的最后一個引數pthread_create()在新創建的執行緒的堆疊上傳遞。當它是一個整數或任何其他大小小于或等于指標大小的東西時,引數可以按原樣通過強制轉換傳遞pthread_create()。但這不是推薦的方法,因為它在機器上不可移植,例如整數與指標的大小不同。讓我們編譯以下簡單程式:
#include <pthread.h>
#include <stdio.h>
void* thread_task(void* arg)
{
printf("Thread received parameter: %d\n", (int)arg);
return NULL;
}
int main(void)
{
pthread_t tid;
int i = 45;
pthread_create(&tid, NULL, thread_task, (void *)i);
pthread_join(tid, NULL);
return 0;
}
gcc 編譯器發出以下警告:
$ gcc pcreate.c -o pcreate -lpthread
pcreate.c: In function ‘thread_task’:
pcreate.c:6:45: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
printf("Thread received parameter: %d\n", (int)arg);
^
pcreate.c: In function ‘main’:
pcreate.c:15:43: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
pthread_create(&tid, NULL, thread_task, (void *)i);
因此,在結構或表條目或動態分配的記憶體區域上使用指標是使其可移植的方法。前面的程式可以修復為:
#include <pthread.h>
#include <stdio.h>
void* thread_task(void* arg)
{
printf("Thread received parameter: %d\n", *((int *)arg));
return NULL;
}
int main(void)
{
pthread_t tid;
int t[1] = { 45 };
pthread_create(&tid, NULL, thread_task, (void *)t);
pthread_join(tid, NULL);
return 0;
}
編譯器不再發出任何警告:
$ gcc pcreate.c -o pcreate -lpthread
$ ./pcreate
Thread received parameter: 45
uj5u.com熱心網友回復:
當您只想傳遞一個整數時,您可以將其強制轉換為指標:
void *foo(void *i) {
int a = (int)i;
}
for ( int i = 0; i < 10; 1 ) {
pthread_create(&thread, 0, foo, (void*)i);
}
這提供了最大的效率并且沒有壽命問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/388577.html
上一篇:兩個執行緒遞增一個數字
下一篇:從分配了觸發器的行訪問資料
