linux创建、取消多线程的简单实用的模板例子

/******************************************************************
 * simple.c -- multithreaded "hello world"
 *
 * Author: Mark Hays <hays@math.arizona.edu>
 */

/* Linux with glibc:
 *   _REENTRANT to grab thread-safe libraries
 *   _POSIX_SOURCE to get POSIX semantics
 */
#ifdef __linux__
#  define _REENTRANT
#  define _POSIX_SOURCE
#endif

/* Hack for LinuxThreads */
#ifdef __linux__
#  define _P __P
#endif

#include <pthread.h>

#include <string.h>	/* for strerror() */

#include <stdio.h>

#define NTHREADS 4

#define errexit(code,str)                          \
  fprintf(stderr,"%s: %s\n",(str),strerror(code)); \
  exit(1);

/******** this is the thread code */
void *hola(void * arg)
{
  int myid=*(int *) arg;

  printf("Hello, world, I'm %d\n",myid);
  return arg;
}

/******** this is the main thread's code */
int main(int argc,char *argv[])
{
  int worker;
  pthread_t threads[NTHREADS];                /* holds thread info */
  int ids[NTHREADS];                          /* holds thread args */
  int errcode;                                /* holds pthread error code */
  int *status;                                /* holds return code */

  /* create the threads */
  for (worker=0; worker<NTHREADS; worker++) {
    ids[worker]=worker;
    if (errcode=pthread_create(&threads[worker],/* thread struct             */
		       NULL,                    /* default thread attributes */
		       hola,                    /* start routine             */
		       &ids[worker])) {         /* arg to routine            */
      errexit(errcode,"pthread_create");
    }
  }
  /* reap the threads as they exit */
  for (worker=0; worker<NTHREADS; worker++) {
    /* wait for thread to terminate */
    if (errcode=pthread_join(threads[worker],(void *) &status)) { 
      errexit(errcode,"pthread_join");
    }
    /* check thread's exit status and release its resources */
    if (*status != worker) {
      fprintf(stderr,"thread %d terminated abnormally\n",worker);
      exit(1);
    }
  }
  return(0);
}

/* EOF simple.c */


更详细的来源:http://math.arizona.edu/~swig/documentation/pthreads/#createdestroy




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值