linux 中多线程使用

来源:互联网 发布:php删除数组重复元素 编辑:程序博客网 时间:2024/04/30 14:24
/* * 对于线程之间的操作: * 一个进程中会有多个线程,各个线程之间的或向切换会付出很小的代价相比于进程之间的切换 * 为什么要引入多线程: * 1.与进程相比,他是一种非常节俭的多任务的操作方式。文们知道,在linux系统下,启动一个新的进程, * 必须分配一个独立的地址空间,建立众多的数据表来维护它的代码段,堆栈段和数据段,这是一种开销和维护成本比较大的多任务工作方式。 * 而运行一个进程中的多个线程,他们彼此之间使用相同的地址空间,共享大部分的数据,启动一个线程花费的时间和空间远小于启动一个进程 * 所花费的空间; * 2.线程间的通信比较方便,对于不同的进程来说,他们具有独立的数据空间,要进行数据传递只能以通信的方式进行,这种方式不仅费时,而且不方便 * 线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其他线程所用。 * 3.提高应用程序的响应; * 4.使多CPU系统更加有效,操作系统会保证当线程数不大于CPU数目时,不同的线程运行在不同的CPU上 * 5.改善程序结构,一个即长有复杂的进程,可以考虑分为多个线程,成为几个独立或半独立的运行部分,这样程序便于理解和修改 * */#include <pthread.h>#include <sys/time.h>#include <string.h>#include <stdio.h>#include <unistd.h>#include <time.h>#include <stdlib.h>#include <sys/types.h>#include <sys/resource.h>#define MAX 10pthread_t thread[2];pthread_mutex_t mut;int number = 0,i;void * thread1(void * ){    printf("thread1 : I'm thread 1\n");    for(i=0; i<MAX; i++)    {        pthread_mutex_lock(&mut);        printf("thread1 : number = %d\n",number);        number++;        pthread_mutex_unlock(&mut);        msleep(1000*100);    }    printf("thread1 :wait the main thread to finish the task?\n");    pthread_exit(NULL);}void * thread2(void * ){    printf("thread2 : I'm thread 2\n");    for(i=0; i<MAX; i++)    {        pthread_mutex_lock(&mut);        printf("thread2 : number = %d\n",number);        number--;        pthread_mutex_unlock(&mut);        msleep(1000*100);    }    printf("thread2 :wait the main thread to finish the task?\n");    pthread_exit(NULL);}void thread_create(void){    int temp;    memset(&thread,0,sizeof(thread));    temp = pthread_create(&thread[0],NULL,thread1,NULL);    if(temp != 0)printf("create thread 1 failed\n");    elseprintf("create thread 1 successful\n");    temp = pthread_create(&thread[1],NULL,thread2,NULL);    if(temp != 0)printf("create thread 2 failed\n");    elseprintf("create thread 2 successful\n");}void thread_wait(void){    if(thread[0] != 0)    {        pthread_join(thread[0],NULL);        printf("thread 1 has finished \n");    }    if(thread[1] != 0)    {        pthread_join(thread[0],NULL);        printf("thread 2 has finished \n");    }}int main(){    pthread_mutex_init(&mut,NULL);    printf("I am the main thread\n");    thread_create();    printf("Main thread wait other thread run\n");    thread_wait();    return 0;}


在我笔记本上的运行结果是:

I am the main threadcreate thread 1 successfulcreate thread 2 successfulMain thread wait other thread runthread2 : I'm thread 2thread1 : I'm thread 1thread2 : number = 0thread1 : number = -1thread2 : number = 0thread1 : number = -1thread2 : number = 0thread1 : number = -1thread1 : number = 0thread2 : number = 1thread2 : number = 0thread1 : number = -1thread2 : number = 0thread1 : number = -1thread1 : number = 0thread2 : number = 1thread2 :wait the main thread to finish the task?thread1 :wait the main thread to finish the task?thread 1 has finished thread 2 has finished