多线程基础:
所有的头文件在nspr4.h中包括了
#include "prinit.h"
//初始化nspr运行库,加载线程组件,在所有线程函数调用前使用
NSPR_API(void) PR_Init(
PRThreadType type, //线程类型
PRThreadPriority priority, //线程运行级别
PRUintn maxPTDs);//无视之,填0
#include "prthread.h"
//以下为nspr提供的线程基本属性
//线程类型
PR_USER_THREAD,
PR_SYSTEM_THREAD
} PRThreadType;
typedef enum PRThreadScope {
PR_LOCAL_THREAD,
PR_GLOBAL_THREAD,
PR_GLOBAL_BOUND_THREAD
} PRThreadScope;
//线程状态(此处不大清楚)
PR_JOINABLE_THREAD,
PR_UNJOINABLE_THREAD
} PRThreadState;
typedef enum PRThreadPriority
{
PR_PRIORITY_FIRST = 0, /* just a placeholder */ //占位
PR_PRIORITY_LOW = 0, /* the lowest possible priority */ //低优先级
PR_PRIORITY_NORMAL = 1, /* most common expected priority */ //正常优先级
PR_PRIORITY_HIGH = 2, /* slightly more aggressive scheduling */ //高优先级
PR_PRIORITY_URGENT = 3, /* it does little good to have more than one */ //超优先级 不要多于一个
PR_PRIORITY_LAST = 3 /* this is just a placeholder */ //占位
} PRThreadPriority;
//线程创建函数
NSPR_API(PRThread*) PR_CreateThread(PRThreadType type,//线程类型
void (PR_CALLBACK *start)(void *arg), //线程函数地址,线程函数和调用
// _beginthread一样最多有一个参数
void *arg, //线程函数的参数
PRThreadPriority priority, //线程运行级别
PRThreadScope scope, //线程运行范围,全局or 局部
PRThreadState state, //线程运行状态
PRUint32 stackSize); //堆栈大小
//原文是"等待目标线程结束, 如果指定线程不能joinable, 返回PR_FAILURE,
//调用此函数会阻塞当前线程,等待当前线程结束",不能有多个线程等待同一个
//线程结束,只会有一个线程等待,而其它立即返回PR_FAILURE, 如果目标线程
//已经终止,等待线程立即返回,而不会阻塞.(可以是判定目标线程再决定是否阻塞)
NSPR_API(PRStatus) PR_JoinThread(PRThread *thread);//指向目标线程.
//原文: 优雅地卸载nspr组件,应由主线程来调用,
//此函数尝试正常关闭进程, 阻塞调用函数,等到user threads数变为0,
//当主线程返回时,进程会立即终止所有子线程(如果有的话),
//此函数返回PR_SUCCESS,如果不是主线程调用,那么就会返回PR_FAILURE
NSPR_API(PRStatus) PR_Cleanup(void);
//例程: (vc2008)
#include "nspr.h"
#pragma comment(lib,"nspr4.lib")
#pragma comment(lib,"plc4.lib")
void Thread_A(char* buf)
{
printf("In thread A: %s\n", buf);
}
void Thread_B(char* buf)
{
printf("In thread B: %s\n", buf);
}
int main(int argc, char* argv[])
{
PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
PRThread* p_tha;
PRThread* p_thb;
p_tha = PR_CreateThread(PR_USER_THREAD,
(void (PR_CALLBACK *)(void *))Thread_A,
"buffer to thread A",
PR_PRIORITY_NORMAL,
PR_LOCAL_THREAD,
PR_JOINABLE_THREAD,
0);
p_thb = PR_CreateThread(PR_USER_THREAD,
(void (PR_CALLBACK *)(void *))Thread_B,
"buffer to thread B",
PR_PRIORITY_NORMAL,
PR_LOCAL_THREAD,
PR_JOINABLE_THREAD,
0);
PR_JoinThread(p_tha);
PR_JoinThread(p_thb);
PR_Cleanup();
return 0;
}