跨平台的线程代码
[ 2006-05-16 15:39:02 | 作者: 痉挛的老鸨 ]
改编自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 | } |
评论Feed: /feed.asp?q=comment&id=35
您可能感兴趣的文章:
监控系统之硬盘录像机(DVR) (痉挛的老鸨 at 2006-07-29)
Thinkpad T60安装 Windows 2003 之完整篇 (progame at 2007-01-19)
Debian安装笔记 (蓝色的雨 at 2007-01-24)
相遇linux (痉挛的老鸨 at 2006-04-12)
从编译Linux kernel说开来 (痉挛的老鸨 at 2006-05-10)
跨平台的移动鼠标代码 (痉挛的老鸨 at 2006-05-17)
FLTK简介 (痉挛的老鸨 at 2006-04-16)
fltk2更新简介 (痉挛的老鸨 at 2006-12-21)
这篇日志没有评论.

