最近在学linux,在看UNIX高级环境编程时,其中有节讲到:linux主线程用线程ID来控制工作线程处理任务

那位高手能给一个例子程序啊?如何创建一个任务队列,主线程如何根据线程ID来控制工作线程来处理线程队列中的任务。

以下是多线程同步的例子
void* thr_test( void* arg ){

  struct msgtype msg;

  int msgid;

  msgid = *((int*)arg);

  printf("msqid = %d IPC_NOWAIT = %d\n", msgid, IPC_NOWAIT);

  time_t tt = time(0)+8;

  //while( time(0) <= tt )

  //{

  msgrcv(msgid, &msg, sizeof(struct msgtype), 1, 0);

  fprintf(stderr,"Server Receive:%s\n", msg.buffer);

  msg.mtype = 2;

  msgsnd(msgid, &msg, sizeof(struct msgtype), 0);

  //}

  pthread_exit( (void*)2 );

  }

  int main(int argc, char **argv)

  {

  struct msgtype msg;

  key_t key;

  int msgid;

  pthread_t tid;

  if(argc != 2)

  {

  fprintf(stderr,"Usage:%s string\n", argv[0]);

  exit(1);

  }

  /*

  char path[256];

  sprintf( path, "%s/", (char*)getenv("HOME") );

  printf( "path is %s\n", path );

  msgid=ftok( path, IPCKEY );

  */

  if((key=ftok(MSG_FILE,'a'))==-1)

  {

  fprintf(stderr,"Creat Key Error:%s\n", strerror(errno));

  exit(1);

  }

  if((msgid=msgget(key, IPC_CREAT | 0666/*PERM*/))==-1)

  {

  fprintf(stderr,"Creat Message Error:%s\n", strerror(errno));

  exit(1);

  }

  pthread_create( &tid, NULL, thr_test, &msgid );

  fprintf(stderr,"msid is :%d\n", msgid);

  msg.mtype = 1;

  strncpy(msg.buffer, argv[1], BUFFER);

  msgsnd(msgid, &msg, sizeof(struct msgtype), 0);

  exit(0);

  }
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-02-08
linux的视频教程可以在CUUG官网上找到,有感兴趣的朋友可以去下载。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网