ACE中同步线程方法

这是ACE中example中的ACE_Barrier方法

下面上代码

// $Id: barrier1.cpp 91671 2010-09-08 18:39:23Z johnnyw $

// This test program illustrates how the ACE barrier synchronization
// mechanisms work.

#include "ace/OS_main.h"
#include "ace/Barrier.h"
#include "ace/Thread_Manager.h"
#include "ace/Service_Config.h"



#if defined (ACE_HAS_THREADS)

struct Tester_Args
	// = TITLE
	//     These arguments are passed into each test thread.
{
	Tester_Args(ACE_Barrier &tb, int i)
	: tester_barrier_(tb),
	n_iterations_(i) {}

	ACE_Barrier &tester_barrier_;
	// Reference to the tester barrier.  This controls each miteration of
	// the tester function running in every thread.

	int n_iterations_;
	// Number of iterations to run.
};

// Iterate <n_iterations> time printing off a message and "waiting"
// for all other threads to complete this iteration.

static void *tester(Tester_Args *args)
{
	for (int iterations = 1;
		iterations <= args->n_iterations_;
		iterations++)
	{
		ACE_DEBUG((LM_DEBUG, "(%t) in iteration %d\n", iterations));

		// Block until all other threads have waited, then continue.
		args->tester_barrier_.wait();
	}

	return 0;
}

// Default number of threads to spawn.
static const int DEFAULT_ITERATIONS = 10;
static const int DEFAULT_THREAD = 2;

int ACE_TMAIN(int argc, ACE_TCHAR *argv[])
{
	ACE_Service_Config daemon(argv[0]);

	int n_threads = argc > 1 ? ACE_OS::atoi(argv[1]) : DEFAULT_THREAD;
	int n_iterations = argc > 2 ? ACE_OS::atoi(argv[2]) : DEFAULT_ITERATIONS;

	ACE_Barrier tester_barrier(n_threads);
	//线程数目
	Tester_Args args(tester_barrier, n_iterations);
	//创建线程
	if (ACE_Thread_Manager::instance()->spawn_n
		(int(n_threads), ACE_THR_FUNC(tester),
		(void *)&args, THR_NEW_LWP | THR_DETACHED) == -1)
		ACE_ERROR_RETURN((LM_ERROR, "%p\n", "spawn_n"), 1);

	// Wait for all the threads to reach their exit point.
	ACE_Thread_Manager::instance()->wait();

	ACE_DEBUG((LM_DEBUG, "(%t) done\n"));
	return 0;
}
#else
int
ACE_TMAIN(int, ACE_TCHAR *[])
{
	ACE_ERROR((LM_ERROR, "threads not supported on this platform\n"));
	return 0;
}
#endif /* ACE_HAS_THREADS */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值