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_5275504018 分钟前
Linux 环境下高效视频切帧的实用指南
linux·运维·音视频
keson要进步20 分钟前
CICD实战(二)-----gitlab的安装与配置
linux·运维·gitlab
ai产品老杨24 分钟前
减少交通拥堵、提高效率、改善交通安全的智慧交通开源了。
前端·vue.js·算法·ecmascript·音视频
我是唐青枫26 分钟前
.NET AOT 详解
java·服务器·.net
小于不是小鱼呀28 分钟前
手撕 K-Means
人工智能·算法·机器学习
m0_7401546729 分钟前
K-Means颜色变卦和渐变色
算法·机器学习·kmeans
藥瓿亭34 分钟前
K8S认证|CKS题库+答案| 4. RBAC - RoleBinding
linux·运维·服务器·云原生·容器·kubernetes·cks
吐泡泡_1 小时前
Linux(线程控制)
linux
东皇太星1 小时前
SIFT算法详细原理与应用
图像处理·算法·计算机视觉
鑫鑫向栄1 小时前
[蓝桥杯]堆的计数
数据结构·c++·算法·蓝桥杯·动态规划