基本概念
线程的创建和销毁
线程同步机制
实例分析: MiniGUI 中的消息传递
其他
===============================================================================
#include <pthread.h>
int pthread_create (pthread_t * thread, pthread_attr_t *
attr, void * (*start_routine)(void *), void * arg);
void pthread_exit (void *retval);
===============================================================================
===============================================================================
#include <pthread.h>
int pthread_join (pthread_t th, void **thread_return);
===============================================================================
===============================================================================
条件变量:
* 可广播, 可设置超时.
* 需要有一个互斥量协作.
===============================================================================
===============================================================================
MiniGUI 的消息结构:
typedef struct _MSG
{
HWND hwnd;
int message;
WPARAM wParam;
LPARAM lParam;
struct timeval time;
POINT pt;
void* pAdd;
}MSG;
typedef MSG* PMSG;
typedef struct _QMSG
{
MSG Msg;
struct _QMSG* next;
BOOL fromheap;
}QMSG;
typedef QMSG* PQMSG;
typedef struct _SYNCMSG
{
MSG Msg;
int retval;
sem_t sem_handle;
struct _SYNCMSG* pNext;
}SYNCMSG;
typedef SYNCMSG* PSYNCMSG;
typedef struct _MSGQUEUE
{
DWORD dwState; // message queue states
pthread_mutex_t lock; // lock
sem_t wait; // wait semaphores
PQMSG pFirstNotifyMsg; // head of the notify message queue
PQMSG pLastNotifyMsg; // tail of the notify message queue
PSYNCMSG pFirstSyncMsg; // head of the sync message queue
PSYNCMSG pLastSyncMsg; // tail of the sync message queue
MSG* msg; // post message buffer
int len; // buffer len
int readpos, writepos; // positions for reading and writing
/*
* One thread can only support eight timers.
* And number of all timers in a MiniGUI applicatoin is 16.
*/
HWND TimerOwner[8]; // Timer owner
int TimerID[8]; // timer identifiers.
BYTE TimerMask; // used timer slots mask
}MSGQUEUE;
-------------------------------------------------------------------------------
* lock 用来实现消息队列的互斥访问
* wait 用来实现 GetMessage 等待消息, 有消息 (PostMessage, SendMessage) 时执行 UP 操作
* 不同进程间的同步消息 (SendMessage) 在 pFirstSyncMsg 上排队, 服务器线程处理之后, 利用
信号量 (sem_handle) 通知客户线程
* 如果利用条件量处理同步消息, 可实现 SendMessageTime 等接口.
===============================================================================
===============================================================================
EXAMPLE:
/* 为每个线程建立局部存储 */
static pthread_key_t con_key;
/* Once-only initialisation of the key */
static pthread_once_t con_key_once = PTHREAD_ONCE_INIT;
/* Allocate the key */
static void con_key_alloc()
{
pthread_key_create (&con_key, NULL);
}
/* Set thread-specific date */
void set_coninfo (void* data)
{
pthread_once (&con_key_once, con_key_alloc);
pthread_setspecific (con_key, data);
}
===============================================================================
![]()