分享

pthread线程参数传递

 wusiqi111 2017-12-07
linux下用C开发多线程程序,Linux系统下的多线程遵循POSIX线程接口,称为pthread。

#include <pthread.h>

int pthread_create(pthread_t *restrict tidp,
                   const pthread_attr_t *restrict attr,
                   void *(*start_rtn)(void), 
                   void *restrict arg);

Returns: 0 if OK, error number on failure

C99 中新增加了 restrict 修饰的指针: 由 restrict 修饰的指针是最初唯一对指针所指向的对象进行存取的方法,仅当第二个指针基于第一个时,才能对对象进行存取。对对象的存取都限定于基于由 restrict 修饰的指针表达式中。 由 restrict 修饰的指针主要用于函数形参,或指向由 malloc() 分配的内存空间。restrict 数据类型不改变程序的语义。 编译器能通过作出 restrict 修饰的指针是存取对象的唯一方法的假设,更好地优化某些类型的例程。

第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。

带线程的编译:gcc -o pthread pthread.c -lpthread
示例1:
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
struct paramSet{
char value[1024];
int length;
};

void *print_message(void *p);
int main(){
pthread_t thread1;//thread2;
struct paramSet msg1;
strcpy(msg1.value,"hello word it is test");
msg1.length = strlen(msg1.value); 
//struct paramSet msg2;
pthread_create(&thread1,NULL,print_message,&msg1);
//pthread_create(&thread2,NULL,print_message,(void *)msg2);
sleep(1);
return 0;

}
void *print_message(void *p){
struct paramSet param;
memset(&param,sizeof(struct paramSet),0);
memcpy(&param,p,sizeof(struct paramSet));
int retval;
printf("threadid=%d\r\n",pthread_self());
printf("%s,%d\r\n",param.value,param.length);
pthread_exit(&retval);

}

示例2:
#include<string.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void *print_message(char *p);
int main(){
pthread_t thread1,thread2;
char msg1[1024]="hello";
    char msg2[1024]="word";

pthread_create(&thread1,NULL,print_message,(void *)msg1);
pthread_create(&thread2,NULL,print_message,(void *)msg2);
sleep(1);
return 0;

}
void *print_message(char *p){
int retval;
printf("threadid=%d\r\n",pthread_self());
printf("%s\r\n",p);
pthread_exit(&retval);

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约