Linux中C语言多线程示例

编译命令:

gcc pThread.c -o Thread -g -lpthread

示例代码:

#include 
#include 
#include 
#include 

pthread_t thread[512];
pthread_mutex_t mut;
#define MAX_THREAD_NUM 5//线程数
//此处说明,创建线程时如果需要传入的参数不止一个,应以结构体的方式传入
struct _PARAM
{
	int iNum = 0;
	char *sMsg = NULL;
}; 

static void *Thread(void *args)
{
	struct _PARAM *temp;

	temp = (struct _PARAM *)args; 
	printf("此%s号为[= %d\t]\n", temp->sMsg, temp->iNum );

	return NULL;
}

int thread_create( )  
{  
	int iRet = 0;
	int i;

	memset(&thread, 0, sizeof(thread ) );

	struct _PARAM *attr;
	attr = (struct _PARAM *)malloc(sizeof(struct _PARAM));
	attr->sMsg = "线程";

	for (i=0;iiNum = i;
		iRet = pthread_create(&thread[i], NULL, Thread, (void *)attr );
		if ( 0 != iRet )
		{
			printf("线程[= %d\t]创建失败!\n", &thread[i] );
			return -1;
		}
		sleep(1);//此处如果不加延时,将会影响到Thread函数接收参数
	}

	return iRet;
}

void thread_wait( )  
{  
	int iRet = 0;
	int i;

	for (i=0;i

后续有时间会编辑成跨平台示例

你可能感兴趣的:(Linux中C编程)