一种简单的跨平台(Linux、Windows)多线程程序实现的例子

 
#include <stdio.h>  
#include <stdlib.h>  
#include <limits.h>  
#include <time.h>  
  
#ifdef _WIN32  
	#include <windows.h>  
	#include <direct.h>  
	#include <io.h>  
	#include <process.h>  
#else  
	#include <unistd.h>  
	#include <getopt.h>  
	#include <sys/types.h>  
	#include <pthread.h>  
#endif  

#define new(Class) (Class*)malloc(sizeof(Class))  

typedef struct ThreadFun ThreadFun;
struct ThreadFun{
	void* params;  //线程函数的参数 
	void* (*fun)(void *params);   //线程函数指针 
};

void mySleep(long ms){
#ifdef _WIN32  
	Sleep(ms);
#else
	usleep(ms);
#endif  	
}

void startThread(int threadNum, ThreadFun funArray[]){

#ifdef _WIN32  
    HANDLE handle[threadNum];
	int i = 0;
	for(i = 0; i < threadNum; i++){
	   handle[i] = (HANDLE) _beginthreadex(NULL, 0, funArray[i].fun, funArray[i].params, 0, NULL); // create thread ok  
	}
	//DWORD dwThread;  
    //HANDLE handle = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)fun,(LPVOID)NULL,0,&dwThread); // create thread ok  
    printf("Win32\n");
	//WaitForMultipleObjects(threadNum, handle, TRUE, INFINITE); //等待这几个线程结束 
    for(i = 0; i < threadNum; i++){
		CloseHandle(handle[i]);    //关闭句柄 
	}
#else  
    
    pthread_mutex_t mutex;
	pthread_cond_t cond;
    pthread_t pt[threadNum];
    int i = 0;
    
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    for(i = 0; i < threadNum; i++){
    	pthread_create(&pt[i], NULL, funArray[i].fun, funArray[i].params); 
	}
//	pthread_exit(0);  //等待全部线程结束函数才结束 
    
#endif  
}

void shit(void *p){
	while(1) {
		printf("%s\n", (char*) p);
		mySleep(1);
	}
}

void* shit2(void *p){
	while(1) {
		printf("%s\n", (char*) p);
		mySleep(1);
	}
}

	
int main(){
	ThreadFun funArr[2];
	funArr[0].fun = shit;
	funArr[0].params = "asdasd";
	funArr[1].fun = shit2;
	funArr[1].params = "111232323";
	startThread(2, funArr);
	while(1){
		printf("shit\n");
		mySleep(1);
	}
	return 0;
}








评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值