zoukankan      html  css  js  c++  java
  • c语言线程中传输多个参数

    前言:c语言中创建一条线程,但是需要传送多个参数给线程的话我们自然会想到通过传送数组或者结构体来实现,下面我们来看看如何在创建线程的时候传送结构体和数组。

     1 #include <stdio.h>
     2 #include <pthread.h>
     3 #include <stdlib.h>
     4 #include <string.h>
     5 
     6 typedef struct Student
     7 {
     8    int num;
     9    char name[10];
    10 }info;
    11 
    12 void *message(void *arg)
    13 {
    14   info *p = (info*)arg;
    15   printf("num:%d name:%s
    ",p->num,p->name);
    16 
    17 }
    18 
    19 void *read_routine1(void *arg)
    20 {    int *fd;
    21     fd = (int*)arg;
    22     // fd[0] = ((int *)arg)[0];
    23     // fd[1] = ((int *)arg)[1];
    24     printf("fd[0]:%d  fd[1]:%d
    ",fd[0],fd[1]);
    25 }
    26 
    27 
    28 int main(int argc,char *argv[])
    29 {    
    30     info *st = (info*)malloc(sizeof(info));
    31     st->num = 10;
    32     strcpy(st->name,"xiaoming");
    33     int fd[2];
    34     fd[0] = 12;
    35     fd[1] = 32;
    36     pthread_t tid1,tid2;
    37     /*创建两条线程,第一条传送的是一个结构体,第二条是数组*/
    38     pthread_create(&tid2,NULL,message,(void*)st);
    39     pthread_create(&tid1,NULL,read_routine1,(void*)fd);
    40     while(1);
    41     free(st);
    42     return 0;
    43 }

     经测试,这种方法是可行的。

  • 相关阅读:
    最小树形图 朱刘算法模板+建边技巧
    模板倍增LCA 求树上两点距离 hdu2586
    【瞎搞题】gym226123 L. For the Honest Election
    【凸包板题】Gym
    集合3
    集合2
    集合1
    常用API&异常
    内部类&API
    多态&接口类&接口
  • 原文地址:https://www.cnblogs.com/wurenzhong/p/8430024.html
Copyright © 2011-2022 走看看