#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{ int threadKind; 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, NULL, 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); //等待这几个线程结束 CloseHandle(handle); //关闭句柄 #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, NULL); } // pthread_exit(0); //等待全部线程结束函数才结束 #endif } void shit(void *p){ while(1) { printf("asdasd\n"); mySleep(1); } } void* shit2(void *p){ while(1) { printf("111232323\n"); mySleep(1); } } int main(){ ThreadFun funArr[2]; funArr[0].fun = shit; funArr[1].fun = shit2; startThread(2, funArr); while(1){ printf("shit\n"); mySleep(1); } return 0; }
一种简单的跨平台(Linux、Windows)多线程程序实现的例子
猜你喜欢
转载自blog.csdn.net/cjzjolly/article/details/80222711
今日推荐
周排行