跨平台的线程代码

跨平台的线程代码

改编自fltk,添加了linux平台下的Sleep实现,只支持Windows和Linux,分别用vc和gcc编译,代码如下:

1 //threads.h, LGPL
2
3 #ifndef Threads_H
4 #define Threads_H
5
6 #ifdef WIN32
7
8 #include < windows.h >
9 #include < process.h >
10
11 typedef unsigned long Fl_Thread;
12
13 static int fl_create_thread(Fl_Thread& t, void *(*f) (void *), void* p)
14 {
15 return t = (Fl_Thread)_beginthread((void( __cdecl * )( void * ))f, 0, p);
16 }
17
18 #else
19
20 // Use POSIX threading...
21 #include < pthread.h >
22 #include < unistd.h >
23
24 typedef pthread_t Fl_Thread;
25
26 static int fl_create_thread(Fl_Thread& t, void *(*f) (void *), void* p)
27 {
28 return pthread_create((pthread_t*)&t, 0, f, p);
29 }
30
31 static void Sleep(unsigned long dwMilliseconds)
32 {
33 usleep(dwMilliseconds * 1000);
34 }
35
36 #endif
37
38 #endif // !Threads_h

使用示例:

1 #include "thread.h"
2 ...
3
4 static Fl_Thread m_thread; // define
5 ...
6
7 // thread create
8 fl_create_thread(m_thread, thread_fun, 0);
9 ...
10
11 static void* thread_fun(void *p)
12 {
13 while (1) {
14 ...
15 }
16
17 return 0;
18 }

你可能感兴趣的:(跨平台的线程代码)