手机站
网通分站
电信主站
密 码:
用户名:
当前位置 : 主页>网站运营>建站经验>列表

POSIX Thread Tutorial

来源:互联网 作者:west263.com 时间:2008-04-16
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!
fprintf(stderr,"%s: %s\n",(str),strerror(code)); \
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; worker

On Linux systems, you compile this program with the command:

        prompt$ cc -o simple simple.c -lpthread

Here'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
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!