操作系统实验五之线程生成Fibonacci数列

一、实验内容

这里写图片描述

二、知识学习

>>pthread_create函数
*原型:**int pthread_create((pthread_t *thread, pthread_attr_t *attr, void start_routine)(void ), void *arg)
用法:#include <pthread.h>
功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。
说明: thread:线程标识符;
   attr:线程属性设置;
   start_routine:线程函数的起始地址;
   arg:传递给start_routine的参数;
   返回值:成功回0;出错,返回-1。
>>pthread_join函数
原型:**int pthread_join(pthread_t thread, (void )value_ptr);
用法:#include <pthread.h>
功能:阻塞当前线程,直到thread对应的线程退出
说明: thread:等待退出线程的线程号。
   value_ptr:退出线程的返回值。
>>pthread_exit函数
原型: void pthread_exit(void *retval
使用:#include <pthread.h>
功能:使用函数pthread_exit退出线程,这是线程的主动行为;由于一个进程中的多个线程是共享数据段的,因此通常在线程退出之后,退出线程所占用的资源并不会随着线程的终止而得到释放,但是可以用pthread_()函数来同步并释放资源。
**说明:**retval:pthread_exit()调用线程的返回值,可由其他函数如pthread_join来检索获取。
>>编译方法
这里写图片描述

三、实验代码

#include <stdio.h>
#include <pthread.h>

#define MAX_SEQUENCE 100

//一组数据,用于创建线程时作为参数传入
struct Data{
     int num; //斐波那契数列的项数
     int Fibo[MAX_SEQUENCE];//最大容量,斐波那契数列
};

void *Fibonacci(void *data){//获得斐波那契数列
    struct Data *tmp = (struct Data*)data;//转化为实际类型
    int i;

    if(  tmp->num == 0 ){
        return;
    }
    if( tmp->num == 1 ){
        tmp->Fibo[0] = 0;
        return;
    }
    tmp->Fibo[0] = 0;
    tmp->Fibo[1] = 1;

    for( i=2; i < tmp->num; i++ ){
        tmp->Fibo[i] = tmp->Fibo[i-1] + tmp->Fibo[i-2]; 
    }
 }

int main(){
    struct Data data;
    pthread_t th;//线程标识符
    int ret; //pthread的返回值 ret = 0,创建线程成功
    int n;
    int i;

    printf("The fibonacci produce programe!\nPlease input an number within 1~200: ");
    scanf("%d", &n);
    if(n < 0 || n > 200){
        printf("Your input is error.");
        return -1;
    }
    data.num = n;//赋值


    //create a thread
    ret = pthread_create(&th, NULL, Fibonacci, (void *)&data);
    if( ret != 0 ){
        printf("Create thread error!\n");
        return -1;
    }

    //阻塞调用线程
    pthread_join( th, NULL);

    //输出斐波那契数列
    if( data.num == 0){
        printf("Nothing output.");
    }
    else{
        printf("The Fibonacci %d items are:\n", data.Fibo[i]);
        }
        printf("\n");
    }
}

四、实验结果

这里写图片描述

  • 9
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kiloveyousmile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值