操作系统原理三线程

线程是进程中的执行流
在这里插入图片描述

线程比进程更节省资源.
线程间的通信比进程间的通信代价小得多.
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>

// 线程函数
void* threadFunc(void* arg){
	sleep(3);
	printf("In NEW thread\n");
}

int main(){
	pthread_t tid; // 线程id

	// 线程创建函数
	pthread_create(&tid,NULL,threadFunc,NULL);

	printf("In main thread\n");


	// 等待指定的线程tid结束
	pthread_join(tid,NULL);

	return 0;
}
#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include<stdlib.h>

int value = 100; // 多个线程共享的数据, 属于进程

// 线程函数
void* hello(void* arg){
    for(int i=0; i<3;i++){
        printf("hello(%d)\n",value++);
        sleep(1);
    }
}

// 线程函数
void* world(void* arg){
    for(int i=0; i<3;i++){
        printf("world(%d)\n",value++);
        sleep(2);
    }
}


int main(){

    // srand(time(NULL));
    pthread_t tid, tid2;
    pthread_create(&tid,NULL,hello,NULL);
    pthread_create(&tid2,NULL,world,NULL);

    pthread_join(tid,NULL);
    pthread_join(tid2,NULL);

    printf("In main thread(%d)\n",value);
}

在这里插入图片描述

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
#include<pthread.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include<omp.h>

void* calculate_pi(void* arg){
    unsigned int seed = time(NULL);
    int circle_points = 0;
    int square_points = 0;
    int interval = *((int*)arg); // 传递的参数

    for(int i = 0; i<interval*interval; ++i){
        double rand_x = (double)rand_r(&seed)/RAND_MAX;
        double rand_y = (double)rand_r(&seed)/RAND_MAX;

        if((rand_x*rand_x + rand_y*rand_y) <= 1){
            circle_points++;
        }

        square_points++;
    }

    double pi = (double)(4.0*circle_points)/square_points;
    printf("The estimated PI is %lf in %d times\n",pi,interval*interval);
    
    pthread_exit(0); // 表示一个线程结束,0表示正常退出
}

int main(int argc, char const *argv[]){
    clock_t start,delta;
    double time_used;

    start = clock();
    
    pthread_t calculate_pi_threads[10];
    int args[10];

    for(int i=0; i<10; i++){
        args[i] = 1000*(i+1);
        //  连续创建多个线程
        pthread_create(calculate_pi_threads+i,NULL,calculate_pi,args+i);
    }

    for(int i=0; i<10; i++){
        // 等待每一个线程结束
        pthread_join(calculate_pi_threads[i],NULL);
    }

    // 等所有线程运行结束,才会执行到这里
    delta = clock() - start;
    printf("The time taken in total: %lf seconds\n", (double)delta/CLOCKS_PER_SEC);
    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值