随笔 - 16, 文章 - 0, 评论 - 55, 引用 - 0
数据加载中……

跨平台的线程代码

改编自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 }

posted on 2006-05-16 16:46 cyantree 阅读(911) 评论(1)  编辑 收藏 引用

评论

# re: 跨平台的线程代码  回复  更多评论   

Boost 也有支持的,快成标准了吧。
2006-05-16 19:33 | Squirrel

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理