C语言中pthread_create函数实现向线程函数传递参数

  #include "apue.h"

  #include

  #include "apueerror.h"

  #include

  #include

  using namespace std;

  pthread_t ntid;

  void printids(const char *s){

  pid_t pid;

  pthread_t tid;

  pid = getpid();

  tid = pthread_self();

  printf("%s pid %lu tid %lu (0x%lx)

  ", s, (unsigned long)pid,

  (unsigned long)tid, (unsigned long)tid);

  }

  struct Param {

  int a;

  int b;

  int c;

  };

  void *thr_fn(void *arg) {

  cout << "----enter sub thread--------" << endl;

  Param tmp = *(Param *)arg;

  cout << "tmp.a=" << tmp.a << endl;

  cout << "tmp.b=" << tmp.b << endl;

  cout << "tmp.c=" << tmp.c << endl;

  printids("new thread: ");

  cout << "Change to C++ code!!" << endl;

  cout << "----exit from sub thread----" << endl;

  return((void *)0);

  }

  int main(void){

  int err;

  int num = 123;

  Param param1;

  param1.a = 11;

  param1.b = 22;

  param1.c = 33;

  //通过结构体向线程函数传入多个参数

  err = pthread_create(&ntid, NULL, thr_fn, ¶m1);

  if (err != 0)

  err_exit(err, "can't create thread");

  printids("main thread:");

  sleep(1);

  exit(0);

  }