linuc 多线程编程(一)
来源:互联网 发布:美西自驾游攻略知乎 编辑:程序博客网 时间:2024/05/18 13:27
第一个单线程,有阻塞#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>void *print(){printf("I am thread\n");}int main(){pthread_t id;pthread_create(&id,NULL,print,NULL);pthread_join(id,NULL);printf("I am main\n");return 0;}运行结果:
I am thread
I am main第二个单线程,无阻塞
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 void *print() 6 { 7 printf("I am thread\n"); 8 } 9 int main() 10 { 11 pthread_t id; 12 pthread_create(&id,NULL,print,NULL); 13 printf("I am main\n"); 14 // pthread_join(id,NULL); 15 return 0; 16 }~执行结果:有:
I am main
和
I am main
I am thread
I am thread
等三、双线程逐一执行
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 void *thread1() 6 { 7 printf("I am thread1\n"); 8 } 9 void *thread2() 10 { 11 printf("I am thread2\n"); 12 } 13 int main() 14 { 15 pthread_t id1,id2; 16 pthread_create(&id1,NULL,thread1,NULL); 17 pthread_join(id1,NULL); 18 pthread_create(&id2,NULL,thread2,NULL); 19 pthread_join(id2,NULL); 20 printf("I am main\n"); 21 return 0; 22 }执行结果:
I am thread1
I am thread2
I am main四、双线程一起执行
执行结果
I am thread2
I am thread1
I am main或
I am thread1
I am thread2
I am main五、双线程读写缓冲区
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <pthread.h> 5 #include<string.h> 6 char buf[50]; 7 void *twrite() 8 { 9 char *st="Hello,write"; 10 strcpy(buf+strlen(buf),st); 11 printf("write success\n"); 12 } 13 void *tread() 14 { 15 printf("read:%s\n",buf); 16 } 17 int main() 18 { 19 pthread_t id1,id2; 20 pthread_create(&id1,NULL,twrite,NULL); 21 pthread_join(id1,NULL); 22 pthread_create(&id2,NULL,tread,NULL); 23 pthread_join(id2,NULL); 24 printf("I am main\n"); 25 return 0; 26 }
执行结果:write success
read:Hello,write
I am main
- linuc 多线程编程(一)
- 多线程编程(一)
- 多线程编程(一)
- #多线程编程(一)
- 多线程编程(一)
- 多线程编程(一)
- Linuc shell编程几大循环与判断
- VC多线程编程一(创建多线程)
- 多线程编程(一)多线程基础
- windows多线程编程(一)
- 多线程编程笔记(一)
- Linux 多线程编程(一)
- Linux多线程编程(一)
- python 多线程编程(一)
- ACE多线程编程(一)
- 多线程编程笔记(一)
- Java5 多线程编程(一)
- Linux 多线程编程(一)
- 一些有用的编程网站:
- 2011-7-29 13:10:40
- Linux下杀掉X
- mysql 慢查询
- hDU 最短路
- linuc 多线程编程(一)
- SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"问题解决
- c语言中的h文件与c文件的理解、编写及使用
- 关于规范xml的xsd文件一点总结
- linux下如何卸载mysql
- My97DatePicker-js日历控件
- SVG与html的交互(svg的js与html的js互调用)
- Oracle中Decode()函数使用技巧
- readv/writev系统调用