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;
}
相关推荐
weixin_5134499619 分钟前
PCA、SVD 、 ICP 、kd-tree算法的简单整理总结
c++·人工智能·学习·算法·机器人
code_pgf29 分钟前
Qwen2.5-VL 算法解析
人工智能·深度学习·算法·transformer
bukeyiwanshui1 小时前
20260417 DNS实验
linux
Code-keys1 小时前
Android Codec2 Filter 算法模块开发指南
android·算法·音视频·视频编解码
无忧智库1 小时前
低空经济新基建:构建低空飞行大数据中心与行业应用算法工厂的全景式蓝图(WORD)
算法
代码中介商1 小时前
Linux 帮助手册与用户管理完全指南
linux·运维·服务器
cccccc语言我来了2 小时前
C++轻量级消息队列服务器
java·服务器·c++
xiaoshuaishuai82 小时前
C# Codex 脚本编写
java·服务器·数据库·c#
闻缺陷则喜何志丹2 小时前
【背包 组合】P7552 [COCI 2020/2021 #6] Anagramistica|普及+
c++·算法·背包·洛谷·组合
Ai173163915793 小时前
GB200 NVL72超节点深度解析:架构、生态与产业格局
大数据·服务器·人工智能·神经网络·机器学习·计算机视觉·架构