#include <stdio.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <signal.h>// void func(int sig)// {// int ret = -1;//// if(sig != SIGIO)// {// return ;// }// }int main(int argc, char **argv){int mousefd = -1;char buf[1024] = {0};//create two process, one to read mouse, and one to read keyboardint ret = -1;ret = fork();if(ret == 0){//son processmousefd = open("/dev/input/mouse0", O_RDONLY);if(mousefd < 0){perror("open");return -1;}while(1){memset(buf, 0, sizeof(buf));ret = read(mousefd, buf, 1024);if(ret > 0){printf("context of mouse: [%s]\n", buf);}}}else if(ret > 0){//parent processwhile(1){memset(buf, 0, sizeof(buf));ret = read(0, buf, 1024); //0 is standard inputif(ret > 0){printf("context of keyboard : [%s]\n", buf);}}}else{perror("fork");}return 0;}
进程技术的缺点:
进程间切换开销大
进程间通信麻烦而且效率低
线程技术保留了进程技术实现多任务的特性
线程的改进就是在线程间切换和线程间通信上提升了效率
多线程在多核心CPU上面更有优势
#include <stdio.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <pthread.h>char buf[1024] = {0};void *func(){int ret = -1;while(1){memset(buf, 0, sizeof(buf));ret = read(0, buf, 1024); //0 is standard inputif(ret > 0){printf("context of keyboard : [%s]\n", buf);}}}int main(int argc, char **argv){int mousefd = -1;//create two process, one to read mouse, and one to read keyboardint ret = -1;pthread_t th = -1;ret = pthread_create(&th, NULL, func, NULL);if(ret != 0){printf("Error: pthread_create");return -1;}//main taskmousefd = open("/dev/input/mouse0", O_RDONLY);if(mousefd < 0){perror("open");return -1;}while(1){memset(buf, 0, sizeof(buf));ret = read(mousefd, buf, 1024);if(ret > 0){printf("context of mouse: [%s]\n", buf);}}return 0;}
Linux中线程简介
线程是参与内核调度的最小单元
一个进程中可以有多个线程
线程的优势:
像进程一样可被OS调度
同一进程的多个线程之间很容易高效率通信
在多核CPU(对称多处理器架构)架构下效率最大化
