libuv多线程处理的简单示例

简介

libuv提供了多线程处理的封装,使用起来也非常简单,一个handle,即uv_thread_t,在linux环境下,就是pthread_t,也就是unsigned long类型。相关的三个函数为

UV_EXTERN int uv_thread_create(uv_thread_t *tid,
    void (*entry)(void *arg), void *arg);
UV_EXTERN unsigned long uv_thread_self(void);
UV_EXTERN int uv_thread_join(uv_thread_t *tid);

下面我们介绍下怎么使用这三个函数

uv_thread_create用来创建一个新的线程uv_thread_self可以获得线程的id(主线程也一样)uv_thread_join则用来等待子线程完成

简单示例

 
  

/*
 * test_thread_equal.cc
 * uv_thread_t is pthread_t, and is type unsigned long int.
 * Created on: 2015年2月5日
 */

#include 
#include 
#include 

uv_thread_t main_thread_id;	//主线程id
uv_thread_t subthreads[2];	//传递给子线程的数据

/**
 * this method will run in subthread.
 * user can translate data from arg.
 * @param arg data from main thread or you can pass subthread's data to main thread.
 */
static void check_thread(void* arg) {
	uv_thread_t *thread_id = (uv_thread_t *)arg;
	uv_thread_t self_id = uv_thread_self();
	printf("main_thread_id:%lu\n", main_thread_id);
	printf("sub_thread_id:%lu\n", self_id);
	*thread_id = uv_thread_self();
}

int main()
{
	uv_thread_t threads[2];
	main_thread_id = uv_thread_self();	//获得当前线程的id

	uv_thread_create(threads + 0, check_thread, subthreads + 0);	//创建子线程
	uv_thread_create(threads + 1, check_thread, subthreads + 1);

	uv_thread_join(threads + 0);	//thread join,阻塞,直到目标子线程执行完成
	uv_thread_join(threads + 1);

	return 0;
}

输出如下
main_thread_id:140123406030656
sub_thread_id:140123389261568
main_thread_id:140123406030656
sub_thread_id:140123380868864

10个线程,计算1-100的和值

/*
 * test_thread_plus.cc
 * uv_thread_t is pthread_t, and is type unsigned long int.
 * Created on: 2015年2月5日
 */

#include 
#include 
#include 

struct thread_data {
	int start;
	int end;	//结束数字
	int result;	//子线程计算结果
};

/**
 * this method will run in subthread.
 * user can translate data from arg.
 * @param arg data from main thread or you can pass subthread's data to main thread.
 */
static void plus_thread(void* arg) {
	thread_data *data = (thread_data *)arg;
	data->result = 0;
	for(int i = data->start; i <= data->end; i++)
	{
		data->result += i;
	}
}

int main()
{
	uv_thread_t threads[10];
	thread_data dataArray[10];
	for(int i = 0; i < 10; i++)
	{
		thread_data* data = dataArray + i;
		data->start = i*10 + 1;
		data->end = (i + 1)*10;
		uv_thread_create(threads + i, plus_thread, data);	//创建子线程
	}

	int sum = 0;
	for(int i = 0; i < 10; i++)
	{
		uv_thread_join(threads + i);	//thread join,阻塞,直到目标子线程执行完成
		thread_data* data = dataArray + i;
		sum += data->result;
	}

	printf("the sum is:%d.\n", sum);
	return 0;
}

输出如下
the sum is:5050.

libuv线程相关的函数,使用起来还是很简单的。

 
  
 
  

你可能感兴趣的:(nodejs,libuv)