上篇博文中,boss线程给其他线程传递的只有一个参数,那么假如是多个参数呢?怎么传递呢?或许你会有这样的疑问,带着这个疑问,我们进入本文的世界,这里传递多个参数,采用结构体,为什么呢?因为结构体里可以根据自己的需要定义多个成员变量,传递过程中,我们只需要将结构体传给线程就可以了。本文分为两部分,第一部分给出代码示例,第二部分给出运行结果。
一、代码示例
#include "StdAfx.h"
#include
#include
#include
#include
#define NUM_THREADS 8
char *messages[NUM_THREADS];
struct thread_data
{
int thread_id;
int sum;
char *message;
};
struct thread_data thread_data_array[NUM_THREADS];
void *PrintHello(void *threadarg)
{
int taskid, sum;
char *hello_msg;
struct thread_data *my_data;
Sleep(1);
my_data = (struct thread_data *) threadarg;
taskid = my_data->thread_id;
sum = my_data->sum;
hello_msg = my_data->message;
printf("Thread %d: %s Sum=%d\n", taskid, hello_msg, sum);
pthread_exit(NULL);
return(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int *taskids[NUM_THREADS];
int rc, t, sum;
sum=0;
messages[0] = "English: Hello World!";
messages[1] = "French: Bonjour, le monde!";
messages[2] = "Spanish: Hola al mundo";
messages[3] = "Klingon: Nuq neH!";
messages[4] = "German: Guten Tag, Welt!";
messages[5] = "Russian: Zdravstvytye, mir!";
messages[6] = "Japan: Sekai e konnichiwa!";
messages[7] = "Latin: Orbis, te saluto!";
for(t=0;t
二、运行结果
![](https://img-blog.csdn.net/20140812085529838?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVsZWkwMDE=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)