#一个简单的线程队列常用函数。
下面是函数说明,需要自己放到一个多线程程序中运行。main函数就自己写下吧。
#define PROCESSID int
#define true 1
#define false 0
#define debug_printf printf("[file %s,line %d] ",__FILE__,__LINE__);/
printf
#define VMP_MAX_MSG_LENGTH 1024
typedef struct VMP_MSG_TYPE_TAG
{
long mtype;
char mtext[VMP_MAX_MSG_LENGTH];
} VmpMsg, *PVmpMsg;
//创建线程队列
//循环测试ID,防止该ID已经被其他程序占用。最大测试次数32
//如果成功返回线程队列的ID,否则,报错
public PROCESSID SysCreatMQ()
{
#define MAX_VMP_MQ_KEY (32)
#define MAGIC_MQ_MSG_QBYTES (7381)
int msgid = 0;
unsigned int key;
int i;
int j;
char *p;
char pName[4]="test";
struct msqid_ds mds;
static unsigned int vmpMqKeysCnt = 0;
static long vmpMqKeys[MAX_VMP_MQ_KEY] = {0};
i = strlen(pName);
if (vmpMqKeysCnt >= MAX_VMP_MQ_KEY)
{
debug_printf("vMP OSAL : constructing new message queue fails due to overflow/n");
return false;
}
/*
Translate all characters(at most 4) of queue name into an unique key
Note: statement j = (long)pName may fail probably.
*/
for (key = 0, p = pName; i; i--, p++)
key = *p | (key << 8);
/* retry 50 at most */
for (j = 0; j < 50; j++)
{
for (i=0; i<vmpMqKeysCnt; i++)
{
if (vmpMqKeys[i] == key)
{
debug_printf("vMP OSAL : constructing new message queue fails because its name is already existed/n");
return false;
}
}
if ((msgid = msgget((key_t)key, IPC_CREAT|IPC_EXCL|0666)) == -1)
{
if ((msgid = msgget((key_t)key, 0)) == -1)
{
return false;
}
if (msgctl(msgid, IPC_STAT, &mds) == -1)
{
return false;
}
if (mds.msg_qbytes == MAGIC_MQ_MSG_QBYTES )
{
if (msgctl(msgid, IPC_RMID, NULL) == -1)
{
return false;
}
}
else
{
key++;
}
}
else
{
mds.msg_qbytes = MAGIC_MQ_MSG_QBYTES;
if (msgctl(msgid, IPC_SET, &mds) == -1)
{
return false;
}
break;
}
}
if (j > 50)
return false;
vmpMqKeys[vmpMqKeysCnt++] = key;
// PROCESSID pQueueId = (PROCESSID)msgid;
debug_printf("id = %d/n",msgid);
return msgid;
}
//从指定的线程队列中获取消息。
//msgrcv函数用法参考man
public int SysGetMessage(
PROCESSID id ,
int availSize,
PVmpMsg pMsg,
int *pMsgLength )
{
debug_printf("to get msg(id:%d)/n", id);
if ((*pMsgLength = msgrcv((int)id, pMsg, availSize, 1, MSG_NOERROR)) == -1)
{
debug_printf("get msg error/n");
return false;
}
debug_printf("end get msg(id:%d)/n", id);
return true;
}
//向指定的线程队列发送消息体。
//msgsnd函数用法参考man
public void SysPutMessage(PROCESSID queueId,int msgLength, PVmpMsg pMsg)
{
debug_printf("start put message %d/n",msgLength);
pMsg->mtype = 1;
if (-1 == msgsnd((int)queueId, pMsg, msgLength, IPC_NOWAIT))
{
debug_printf("put message error/n");
return;
}
debug_printf("end put message %d/n",msgLength);
return;
}
只是一个简单的记录,便于以后使用。