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;
}
相关推荐
铉铉这波能秀5 分钟前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
释怀不想释怀6 分钟前
Linux文件上传(rz)和下载(sz)压缩(tar.gz)和解压(zip)
linux·运维·服务器
蜡笔小马14 分钟前
10.Boost.Geometry R-tree 空间索引详解
开发语言·c++·算法·r-tree
IOsetting15 分钟前
金山云主机添加开机路由
运维·服务器·开发语言·网络·php
酉鬼女又兒20 分钟前
零基础入门Linux指南:每天一个Linux命令_sed
linux·运维·服务器
唐梓航-求职中23 分钟前
编程-技术-算法-leetcode-288. 单词的唯一缩写
算法·leetcode·c#
daad77724 分钟前
tcpdump_BPF
linux·测试工具·tcpdump
仟濹25 分钟前
【算法打卡day3 | 2026-02-08 周日 | 算法: BFS】3_卡码网99_计数孤岛_BFS | 4_卡码网100_最大岛屿的面积DFS
算法·深度优先·宽度优先
予枫的编程笔记27 分钟前
【Linux进阶篇】Linux网络配置+端口监听实战:ip/ss/iptables常用命令一次吃透
linux·iptables·网络配置·curl·端口监听·ping·ss命令
Ll130452529828 分钟前
Leetcode二叉树part4
算法·leetcode·职场和发展