linux下的C语言开发(线程等待)

Python010

linux下的C语言开发(线程等待),第1张

姓名:冯成  学号:19020100164  学院:丁香二号书院

转自: https://feixiaoxing.blog.csdn.net/article/details/7240833

【 嵌牛导读 】本文将介绍linux下的C语言开发中的线程等待

【 嵌牛鼻子 】linux C语言 线程等待

【 嵌牛提问 】linux下的C语言开发中的线程等待是什么?

和多进程一样,多线程也有自己的等待函数。这个等待函数就是pthread_join函数。那么这个函数有什么用呢?我们其实可以用它来等待线程运行结束。

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>

#include <stdlib.h>

void func(void* args)

{

    sleep(2)

    printf("this is func!\n")

}

int main()

{

    pthread_t pid

    if(pthread_create(&pid, NULL, func, NULL))

    {

        return -1

    }

    pthread_join(pid, NULL)

    printf("this is end of main!\n")

    return 0

}

    编写wait.c文件结束之后,我们就可以开始编译了。首先你需要输入gcc wait.c -o wait -lpthread,编译之后你就可以看到wait可执行文件,输入./wait即可。

[test@localhost thread]$ ./thread

this is func!

this is end of main!

3个线程使用的都是同一个info

代码 Info_t *info = (Info_t *)malloc(sizeof(Info_t))只创建了一个info

pthread_create(&threads[i],NULL,calMatrix,(void *)info)三个线程使用的是同一个

我把你的代码改了下:

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

int mtc[3] = { 0 } // result matrix

typedef struct

{

    int prank

    int *mta 

    int *mtb

}Info_t

void* calMatrix(void* arg)

{

    int i

    Info_t *info = (Info_t *)arg

    int prank = info->prank

    fprintf(stdout,"calMatrix : prank is %d\n",prank)

    for(i = 0 i < 3 i++)

        mtc[prank] += info->mta[i] * info->mtb[i]

    return NULL

}

int main(int argc,char **argv)

{

    int i,j,k = 0

    int mta[3][3]

    int mtb[3] = { 1 }

    Info_t *info = (Info_t *)malloc(sizeof(Info_t)*3)

    for(i = 0 i < 3 i++)

        for(j = 0 j < 3 j++)

            mta[i][j] = k++

    /* 3 threads */

    pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t)*3)

    fprintf(stdout,"\n")fflush(stdout)

    for(i = 0 i < 3 i++)

    {

        info[i].prank = i

        info[i].mta = mta[i]

        info[i].mtb = mtb

        pthread_create(&threads[i],NULL,calMatrix,(void *)(&info[i]))

    }

    for(i = 0 i < 3 i++)

        pthread_join(threads[i],NULL)

    fprintf(stdout,"\n==== the matrix result ====\n\n")

    fflush(stdout)

    for(i = 0 i < 3 i++)

    {

        fprintf(stdout,"mtc[%d] = %d\n",i,mtc[i])

        fflush(stdout)

    }

    return 0

}

矩阵的计算我忘记了,你运行看看结果对不对

#include #include #include typedef struct datanode {char name[24]char phone[12]// ......struct datanode *next}*pNode,*LinkList,NodeLinkList getEmptyList() {LinkList head = (pNode)malloc(sizeof(Node))head->next = NULLretur...