线程有时称为轻权进程(lightweight process)
同一进程内的所有线程共享相同的全局内存。这使得线程之间易于共享信息,然后这样也会带来同步的问题
同一进程内的所有线程处理共享全局变量外还共享:
1.进程指令
2.大多数数据
3.打开的文件(即描述符)
4.信号处理函数和信号处置
5.当前工作目录
6.用户ID和组ID
不过每个线程有各自的:
1.线程ID
2.寄存器集合,包括程序计数器和栈指针
3.栈(用于存放局部变量和返回地址)
4.errno
5.信号掩码
6.优先级
基本线程函数
有关线程的一些用法跟概念可以查看之前apue的笔记 http://www.cnblogs.com/runnyu/p/4643363.html
下面只列出这些函数的原型
#include <pthread.h> int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr,void *(*start_rtn)(void *),void *restrict arg); int pthread_join(pthread_t thread,void **rval_ptr); pthread_t pthread_self(void); int pthread_detach(pthread_t tid); void pthread_exit(void *rval_ptr);
使用线程的str_cli函数
我们使用线程把第五章中使用fork的str_cli函数重新编写成改用线程
1 #include "unpthread.h" 2 3 void *copyto(void *); 4 5 static int sockfd; /* global for both threads to access */ 6 static FILE *fp; 7 8 void 9 str_cli(FILE *fp_arg, int sockfd_arg) 10 { 11 char recvline[MAXLINE]; 12 pthread_t tid; 13 14 sockfd = sockfd_arg; /* copy arguments to externals */ 15 fp = fp_arg; 16 17 Pthread_create(&tid, NULL, copyto, NULL); 18 19 while (Readline(sockfd, recvline, MAXLINE) > 0) 20 Fputs(recvline, stdout); 21 } 22 23 void * 24 copyto(void *arg) 25 { 26 char sendline[MAXLINE]; 27 28 while (Fgets(sendline, MAXLINE, fp) != NULL) 29 Writen(sockfd, sendline, strlen(sendline)); 30 31 Shutdown(sockfd, SHUT_WR); /* EOF on stdin, send FIN */ 32 33 return(NULL); 34 /* 4return (i.e., thread terminates) when EOF on stdin */ 35 }