跨平台的线程代码

[ 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
11typedef unsigned long Fl_Thread;
12
13static 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
24typedef pthread_t Fl_Thread;
25
26static 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
31static 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
4static Fl_Thread m_thread; // define
5...
6
7// thread create
8fl_create_thread(m_thread, thread_fun, 0);
9...
10
11static void* thread_fun(void *p)
12{
13 while (1) {
14 ...
15 }
16
17 return 0;
18}
评论Feed 评论Feed: /feed.asp?q=comment&id=35

这篇日志没有评论.


发表
表情图标
[smile] [confused] [cool] [cry]
[eek] [angry] [wink] [sweat]
[lol] [stun] [razz] [redface]
[rolleyes] [sad] [yes] [no]
[heart] [star] [music] [idea]
UBB代码
转换链接
表情图标
悄悄话
用户名:   密码:   (非注册用户不需要输入密码) 注册?
验证码(不区分大小写) * 请输入验证码