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;
}
相关推荐
真命天子_重庆_中国1 分钟前
记一次生产服务器磁盘I/O性能瓶颈与负载过高分析与处理
运维·服务器
瑶总迷弟4 分钟前
使用 Docker 和 docker-compose 快速部署 openGauss
linux·数据库·云原生·eureka
携欢9 分钟前
PortSwigger靶场之CSRF where token is tied to non-session cookie通关秘籍
运维·服务器·前端
BothSavage19 分钟前
Ubuntu-8卡H20服务器升级nvidia驱动+cuda版本
linux·服务器·ubuntu·gpu·nvidia·cuda·nvcc
清风wxy22 分钟前
C语言基础数组作业(冒泡算法)
c语言·开发语言·数据结构·c++·windows·算法
IT小番茄22 分钟前
Kubernetes云平台管理实战:如何创建Deployment更好(九)
算法
---学无止境---25 分钟前
Linux中异常初始化和门设置函数的实现
linux
waves浪游26 分钟前
基础开发工具(上)
linux
白云千载尽39 分钟前
leetcode 2598 执行操作后最大MEX
算法·leetcode·职场和发展
岁月向前1 小时前
网络数据大端序和小端序
算法