linuxc多线程参数传递

本文展示了一个使用C语言进行多线程编程的例子,通过创建三个不同的线程并分别传递不同类型的参数,演示了如何在多线程环境中共享数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <pthread.h>

struct stu  
{  
      int age;
      char *name;
      char *num;
};  

void thread1(void)
{
      int i;
      for(i=0;i<3;i++)
      {
            printf("This is a pthread1.\n");
            usleep(2);
      }
}

//传递多个参数
void thread2(void *data)
{
      struct stu *stu1=(struct stu*)data;
      int i;
      for(i=0;i<3;i++)
      {
            printf("This is a pthread2. age=%d,name=%s,num=%s\n",stu1->age,stu1->name,stu1->num);
            usleep(1);
      }
}

//传递一个参数
void thread3(void *data)
{
      //int *d=(int *)data;
      char *d=(char *)data;
      int i;
      for(i=0;i<3;i++)
      {
            printf("This is a pthread3. data=%s\n",d);
            usleep(1);
      }
}



int main(void)
{
      pthread_t id1,id2,id3;
      int i,ret;
      ret=pthread_create(&id1,NULL,(void *) thread1,NULL);
      if(ret!=0){
            printf ("Create pthread1 error!\n");
            exit (1);
      }
      struct stu student;
      student.age=10;
      student.name="yuguoqing";
      student.num="0415214736";
      ret=pthread_create(&id2,NULL,(void *) thread2,(void *)&student);
      if(ret!=0){
            printf ("Create pthread2 error!\n");
            exit (1);
      }

      //int data=123; 传递整数应为(void *)&data
      char *data;
      data="i am yu";           
      ret=pthread_create(&id3,NULL,(void *) thread3,(void *)data);
      if(ret!=0){
            printf ("Create pthread3 error!\n");
            exit (1);
      }
      sleep(1);

      return (0);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值