Linux 進程與線程六

來源:互聯網
上載者:User

標籤:參數   errno.h   建立   for   exit()函數   rgs   failed   div   返回   

//線程間的通訊#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <pthread.h>/*線程1與控制線程通訊方法1--全域變數*/int g_num=10;void *thread_run(void *arg){    //線程1被分離了,但最好不要使用pthread_join()函數接受,多線程下報錯記憶體溢出    pthread_detach(pthread_self());    int *p=(int *)arg;    (*p)++;    g_num=12;    /*線程1與控制線程通訊方法2--pthread_exit()函數的參數*/    //pthread_exit(p);    //執行pthread_exit()函數後,線程會直接退出    printf("線程1退出了!\n");    /*線程1與控制線程通訊方法3--線程中return*/    return p;}int main(int arg,char *args[]){    /*     * 每個線程都擁有各自的棧記憶體,但是彼此之間的棧記憶體是可以互相訪問,     * 比如在控制線程定義的變數,可以線上程1中訪問     * 線程1中定義變數可能無法在控制線程訪問,因為無法確定變數是否因為線程執行完畢被釋放了     * */    int index=0;    pthread_t thr1;    if(pthread_create(&thr1,NULL,thread_run,&index)!=0)    {        printf("pthread_create() failed !\n");        return -1;    }    //等待線程1    int *p=NULL;    pthread_join(thr1,(void **)&p);    printf("線程1的傳回值%d\n",*p);    printf("控制線程的index=%d\n",index);    printf("g_num=%d\n",g_num);    return 0;}

 

//線程的並存執行#include <stdio.h>#include <stdlib.h>#include <string.h>#include <errno.h>#include <unistd.h>#include <pthread.h>void *thread_run(void *arg){    //pthread_detach(pthread_self());    if (arg != NULL)    {        int *p = (int *) arg;        int i = 0;        for (i = 0; i < *p; i++)        {            printf("這是線程%d的第%d圈!\n", (int) pthread_self(), i);            sleep(1);        }    }    return NULL;}int main(int arg, char *args[]){    int i = 0;    int num1 = 10;    int num2 = 10;    printf("請輸入建立線程的個數:\n");    scanf("%d", &num1);    printf("請輸入每個線程的圈數:\n");    scanf("%d", &num2);    pthread_t thrs[200];    /*     * 多線程是並行啟動並執行     * */    for (i = 0; i < num1; i++)    {        if (pthread_create(&thrs[i], NULL, thread_run, &num2) != 0)        {            printf("pthread_create() failed !\n");            return -1;        }    }    for (i = 0; i < num1; i++)    {        /*如果沒有pthread_join(),那麼控制線程不會等待子線程,會直接退出*/        pthread_join(thrs[i],NULL);    }    return 0;}

 

Linux 進程與線程六

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.