C语言多线程练练手

C语言代码如下,注释是写给自己的,怕自己以后忘了。
练习函数:
#include <pthread.h>
pthread_create(&th1, NULL, pthread_op, &pthr1);
pthread_join(th1, NULL);
pthread_cancel(th1);
pthread_testcancel();


```c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

//该test实现了:当某一线程完成任务时,自动中断其他线程并释放。然后开始执行下一个任务,最后返回执行时间。
//该代码只是用于练练手,是大二下学期写的区块链代码project4的废案之一.

#define place1 0;
#define place2 40240;
#define place3 30480;

int flag = 0;

typedef struct {
    int a;
    int Nonce_2;
} pthr;

void *pthread_op(void *p) {
    pthr *a = (pthr *)p;
    while (a->Nonce_2 != 40999) {
        a->Nonce_2++;
        pthread_testcancel();
    }
    flag = 1;
    printf("%d compelete!\n", a->a);
    // sleep(1);
}

int main() {
    clock_t start,
        finish;  //定义第一次调用CPU时钟单位的实际,可以理解为定义一个计数器
    double Total_time;  //定义一个double类型的变量,用于存储时间单位
    start = clock();
    pthr pthr1, pthr2, pthr3;
    pthr1.Nonce_2 = place1;
    pthr3.Nonce_2 = place3;
    pthr2.Nonce_2 = place2;  //令不同线程从不同位置开始计算sha256
    pthread_t th1, th2, th3;
    int n, num;
    printf("how many block: ");
    scanf("%d", &num);
    // n为区块编码
    for (n = 1; n < num + 1; n++) {
        flag = 0;
        pthr1.a = 1;
        pthr2.a = 2;
        pthr3.a = 3;
        pthread_create(&th1, NULL, pthread_op, &pthr1);
        pthread_create(&th2, NULL, pthread_op, &pthr2);
        pthread_create(&th3, NULL, pthread_op, &pthr3);
        while (1) {
            if (flag == 1) {
                pthread_cancel(th1);
                pthread_cancel(th2);
                pthread_cancel(th3);
                break;
            }
        }
        pthread_join(th1, NULL);
        pthread_join(th2, NULL);
        pthread_join(th3, NULL);
    }
    finish = clock();
    Total_time = (double)(finish - start) / CLOCKS_PER_SEC;
    printf("running time:%0.3fms ", Total_time);
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值