Linux——线程练习

1.创建一个多线程程序,至少有10个子线程,

每个线程有会打印不同的数据,同时表明身份

cs 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

typedef void* (*PFUN)(void* );


void* th1(void*arg)
{
    printf("subthread id%lu\n",pthread_self());
    pthread_exit(0);
}
void* th2(void*arg)
{
    printf("subthread id%lu\n",pthread_self());
    pthread_exit(0);
}
void* th3(void*arg)
{
    printf("subthread id%lu\n",pthread_self());
    pthread_exit(0);
}
int main(int argc, char *argv[])
{
    int i = 0 ;
    PFUN th[5]={th1,th2,th3,th2,th1};
    pthread_t tid[5]={0};
    for(i = 0 ;i<5;i++)
    {
        pthread_create(&tid[i],NULL,th[i],NULL);
    }

    for(i=0;i<5;i++)
    {
        pthread_join(tid[i],NULL);
    }
    return 0;
}

typedef strcut

{

float a;

float b;

char c;//+ - * /

float d;

}JSQ;

主线程,接收一个表达式,填充结构体,传递给th1线程,th1线程结算结果,并返回给主线程。主线程输出结果。

cs 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
typedef struct
{
    float a;
    float b;
    char c;//+ - * /
    float d;
}JSQ;
void* th3(void*arg)
{
    printf("subthread id%lu\n",pthread_self());
    JSQ*tmp = (JSQ*)arg;
    switch(tmp->c)
    {
        case '+' :
            tmp->d  = tmp->a+tmp->b;
            break;
        case '-' :
            tmp->d  = tmp->a-tmp->b;
            break;
        case '*' :
            tmp->d  = tmp->a*tmp->b;
            break;
        case '/' :
            tmp->d  = tmp->a/tmp->b;
            break;
    }

    pthread_exit(tmp);
}
int main(int argc, char *argv[])
{
    int i = 0 ;
    pthread_t tid;
    JSQ jsq;
    // 2.3 + 5.4  atof;
    jsq.a  =2.3;
    jsq.b  = 5.4;
    jsq.c = '+';

    pthread_create(&tid,NULL,th3,&jsq);
    void* ret;
    pthread_join(tid,&ret);
    printf("result is %f\n", ((JSQ*)ret)->d);
    return 0;
}
相关推荐
千金裘换酒10 小时前
LeetCode 二叉树的最大深度 递归+层序遍历
算法·leetcode·职场和发展
爱敲代码的TOM10 小时前
详解一致性哈希算法
算法·哈希算法
lzllzz2310 小时前
递归的理解
算法·深度优先·图论
陈让然10 小时前
WSL2 ubuntu18.04扩容
linux·运维·ubuntu
PoppyBu11 小时前
ubuntu20.04安装amule
linux·ubuntu
Exquisite.11 小时前
云原生高级前置复习
linux·云原生·云计算
HIT_Weston11 小时前
94、【Ubuntu】【Hugo】搭建私人博客:面包屑(二)
linux·运维·ubuntu
小O的算法实验室11 小时前
2024年IEEE TITS SCI2区TOP,考虑无人机能耗与时间窗的卡车–无人机协同路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
派森先生11 小时前
排序算法-选择排序
算法·排序算法
C雨后彩虹11 小时前
书籍叠放问题
java·数据结构·算法·华为·面试