31: exit(1);32: 33: /******** this is the thread code */34: void *hola(void * arg)35: {36: int myid=*(int *) arg;37: 38: printf("Hello, world, I'm %d\n",myid);39: return arg;40: }41: 42: /******** this is the main thread's code */43: int main(int argc,char *argv[])44: {45: int worker;46: pthread_t threads[NTHREADS]; /* holds thread info */47: int ids[NTHREADS]; /* holds thread args */48: int errcode; /* holds pthread error code */49: int *status; /* holds return code */50: 51: /* create the threads */52: for (worker=0; workerOn Linux systems, you compile this program with the command:
prompt$ cc -o simple simple.c -lpthreadHere's a blow-by-blow account of what is going on. The program starts in main() on line 43. It will create NTHREADS threads (NTHREADS is defined on line 27) on line 54, each of which starts executing the function hola() on line 34. The main thread waits for each of the worker threads to terminate by calling pthread_join() for each thread on line 64. Meanwhile, each of the worker threads prints a message and its thread ID and then exits. Once the main thread has reaped all of the workers, the main program exits.
Now for the details. Threads are created with the pthread_create() call. The first argument is a pointer to a pthread_t -- an opaque data structure (i.e., it is a black box) that describes the thread. Each thread must have a unique pthread_t to describe it. In this case, we store the descriptor for each thread in the array threads[] defined on line 46. The second argument to pthread_create() is of type pthread_attr_t and specifies the attributes of the thread being created (scheduling priority, etc). Normally you can use the value
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




