Как передать несколько параметров в поток в C - PullRequest
11 голосов
/ 22 ноября 2011

Я пытаюсь передать два параметра потоку в C. Я создал массив (размером 2) и пытаюсь передать этот массив в поток. Это правильный подход для передачи нескольких параметров в поток?

// parameters of input. These are two random numbers 
int track_no = rand()%15; // getting the track number for the thread
int number = rand()%20 + 1; // this represents the work that needs to be done
int *parameters[2];
parameters[0]=track_no;
parameters[1]=number;

// the thread is created here 
pthread_t server_thread;
int server_thread_status;
//somehow pass two parameters into the thread
server_thread_status = pthread_create(&server_thread, NULL, disk_access, parameters);

Ответы [ 2 ]

18 голосов
/ 22 ноября 2011

Поскольку вы передаете пустой указатель, он может указывать на что угодно, включая структуру, в соответствии со следующим примером :

typedef struct s_xyzzy {
    int num;
    char name[20];
    float secret;
} xyzzy;

xyzzy plugh;
plugh.num = 42;
strcpy (plugh.name, "paxdiablo");
plugh.secret = 3.141592653589;

status = pthread_create (&server_thread, NULL, disk_access, &plugh);
// pthread_join down here somewhere to ensure plugh
//   stay in scope while server_thread is using it.
1 голос
/ 22 ноября 2011

Это один из способов.Другой обычный способ - передать указатель на struct.Таким образом, вы можете иметь разные типы «параметров», и параметры именуются, а не индексируются, что иногда делает код немного легче для чтения / отслеживания.

...