/*枚举常量mtx_recursive范例*/
#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
#define NUMBER 5
mtx_t mutex;
int shared_sum = 0; //所有线程累积的和。
/*二叉树节点结构。*/
typedef struct node{
int number;
struct node *left;
struct node *right;
} Node;
/*创建二叉树新节点函数。*/
Node *create_node(int number)
{
Node *new_node = (Node *)malloc(sizeof(Node));
if(new_node==NULL)
{
fprintf(stderr, "Memory allocation failed.\n");
return NULL;
}
else
{
new_node->number = number;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
}
/*创建二叉树函数。*/
Node *create_binary_tree(const int *ptr)
{
Node *root = create_node(ptr[0]);
root->left = create_node(ptr[1]);
root->right = create_node(ptr[2]);
root->left->left = create_node(ptr[3]);
root->left->right = create_node(ptr[4]);
root->right->left = create_node(ptr[5]);
root->right->right = create_node(ptr[6]);
return root;
}
/*递归遍历二叉树函数。*/
void traverse_binary_tree(Node *root, int depth)
{
if(root==NULL)
return;
mtx_lock(&mutex);
shared_sum += root->number;
printf("Thread %lX: node %2d depth %d sum %3d\n", \
thrd_current(), root->number, depth, shared_sum);
/*递归遍历子树。*/
traverse_binary_tree(root->left, depth+1);
traverse_binary_tree(root->right, depth+1);
mtx_unlock(&mutex);
}
/*释放二叉树函数。*/
void free_binary_tree(Node *root)
{
if(root==NULL)
return;
free_binary_tree(root->left);
free_binary_tree(root->right);
free(root);
}
/*新线程函数。*/
int thread_func(void *arg)
{
traverse_binary_tree((Node *)arg,0);
return 0;
}
int main(void)
{
thrd_t thread1, thread2;
const int arr1[] = {3,6,9,12,15,18,21};
const int arr2[] = {2,4,6,8,10,12,14};
/*创建二叉树。*/
Node *tree1 = create_binary_tree(arr1);
Node *tree2 = create_binary_tree(arr2);
/*初始化递归锁。*/
if(mtx_init(&mutex, mtx_plain | mtx_recursive) != thrd_success)
{
fprintf(stderr, "mtx_init failed.\n");
exit(EXIT_FAILURE);
}
/*创建线程遍历二叉树。*/
if(thrd_create(&thread1, thread_func, tree1) != thrd_success)
{
fprintf(stderr, "thrd_create for thread1 failed.\n");
exit(EXIT_FAILURE);
}
if(thrd_create(&thread2, thread_func, tree2) != thrd_success)
{
fprintf(stderr, "thrd_create for thread2 failed.\n");
exit(EXIT_FAILURE);
}
/*连接线程。*/
thrd_join(thread1, NULL);
thrd_join(thread2, NULL);
/*销毁互斥。*/
mtx_destroy(&mutex);
/*释放二叉树内存。*/
free_binary_tree(tree1);
free_binary_tree(tree2);
printf("Total sum: %d\n", shared_sum);
return 0;
}
|