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

📄 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 <unistd.h>

#include "Pi2API.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++)
		{
		PISync_lock( pSync );
		cout << "This is thread #" << (void *)pThread << " in loop " << i
			<< endl;
		if ( i==8 )
			{
			PISync_unlock( pSync );
			PIThread_terminate( pThread, 37 );	
			};
		PISync_unlock( pSync );
		};
	return 0;
}

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

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

	enum { MAX_THREADS = 10 };
	PIThread *aThreads[ MAX_THREADS ];
	int iNumThreads = 0;
	PIThread_setPriority( PIThread_getCurrent(), PITHREAD_PRIORITY_HIGH );
	if ( pSync )
		{
		PISync_lock( pSync );
		int bOK = 1;
		for( ; bOK && (iNumThreads < MAX_THREADS); iNumThreads++ )
			{
			PIThread *pThread = PIThread_new( 0, 0 );
			PIThread_begin( pThread, thread_fn, (unsigned long)pSync,
				PITHREAD_PRIORITY_NORMAL, 0 );
			if ( !pThread )
				{
				cerr << "Error allocating thread " << endl;
				bOK = 0;
				}
			else
				{
				aThreads[ iNumThreads ] = pThread;
				PIThread_setPriority( pThread, iNumThreads % 4 );
				};
			};
		PISync_unlock( pSync );
		};

	PIThread_dbgDump( 0 );

	/* --- wait for all threads to die --- */
	for( int i=0; i < iNumThreads; i++ )
		{
		PIThread *pThread = aThreads[i];
		PIThread_delete( pThread );
		cout << (void *)pThread << " killed " << endl;
		};

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

	iRet = 0;
}

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

	return iRet;
}

⌨️ 快捷键说明

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