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;
}