⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 step3.cpp

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 CPP
字号:

/*
 * Step3: generate a mutex and multiple threads. Tests synchronization
 * thread creation, termination deletion.
 */

#include <stdlib.h>
#include <iostream.h>
#include <string.h>

#include "PiAPI.h"
#include "TestOS.h"

unsigned long thread_fn( unsigned long ulData )
{
	PISync *pSync = (PISync *)ulData;
	cout << "pSync is " << (void *)pSync << endl;
	PIThread *pThread = PIThread_getCurrent();
	for(int i=0; i<10; i++)
		{
		if ( PISync_lock( pSync ) ) { FAILED(1); return 0; };
		int iPriority;
		if ( PIThread_getPriority( pThread, &iPriority ) )
			{ FAILED(10); return 0; };
		cout << "This is thread #" << (void *)pThread
			<< ", priority(" << iPriority
			<< ") in loop " << i << endl;
		if ( i==8 )
			{
			if ( PISync_unlock( pSync ) ) { FAILED(3); return 0; };
			if ( PIThread_terminate( pThread, 37 ) ) { FAILED(4); return 0; };
			};
		if ( PISync_unlock( pSync ) ) { FAILED(2); return 0; };
		};
	return 0;
}

int iRet;
void Step3()
{
	cout << "Program running on " << PIPlatform_getDescription() << endl;

	PISync *pSync = 0;
	if ( !( pSync = PIPlatform_allocLocalMutex() ) )
		{
		FAILED(5);
		cout << "Unable to allocate mutex" << endl;
		};

	enum { MAX_THREADS = 5 };
	PIThread *aThreads[ MAX_THREADS ];
	int iNumThreads = 0;
	PIThread_setPriority( PIThread_getCurrent(), PITHREAD_PRIORITY_HIGH );
	if ( pSync )
		{
		if ( PISync_lock( pSync ) ) { FAILED(6); return; };
		int bOK = 1;
		for( ; bOK && (iNumThreads < MAX_THREADS); iNumThreads++ )
			{
			PIThread *pThread = PIThread_new( 0, 0 );
			if ( PIThread_begin( pThread, thread_fn, (unsigned long)pSync,
				PITHREAD_PRIORITY_MED, 0 ) )
				{
				cout << "Error starting thread" << endl;
				iRet = -1; return;
				};
			if ( !pThread )
				{
				cout << "Error allocating thread " << endl;
				bOK = 0;
				}
			else
				{
				cout << "Thread started " << endl;
				aThreads[ iNumThreads ] = pThread;
				PIThread_setPriority( pThread, iNumThreads % 5 );
				};
			};
		if ( PISync_unlock( pSync ) ) { FAILED(7); };
		};

	PIThread_dbgDump( 0 );

	/* --- kill all the threads --- */
	for( int i=0; i < iNumThreads; i++ )
		{
		PIThread *pThread = aThreads[i];
		if ( PIThread_delete( pThread ) )
			{ FAILED(8); };
		cout << (void *)pThread << " killed " << endl;
		};

	if ( pSync )
		{ if ( PISync_delete( pSync ) ) { FAILED(9) }; };

	OK;
	iRet = 0;
}

int main()
{
	if ( PIPlatform_enter( "dummy", PIPLATFORM_VERSION_1_0, Step3 ) )
		{
		cout << "Platform_enter() failed." << endl;
		exit( 1 );
		};

	return iRet;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -