|
要想编写多线程,那就要使用锁。而在软件编写中,数据结构是少不了的。所以,我们在编写多线程的时候,就需要考虑一下如何在数据结构中插入锁。当然,有些数据结构是没有锁的,所以自然这个锁并不一定是必须的。
比如说,我们编写一个多线程堆栈,应该怎么做呢,- typedef struct _STACK
- {
- void* pData;
- int maxLen;
- int top;
- void* hLock;
-
- STATUS (*push)(struct _STACK* pStack, void* pData, int size);
- STATUS (*pop)(struct _STACK* pStack, void* pData, int size);
复制代码 (1) 初始化操作- STACK* get_new_stack(void* pData, int len, void* pLock)
- {
- STACK* pStack;
-
- if(NULL == pData || 0 == len)
- return NULL;
-
- pStack = (STACK*)malloc(sizeof(STACK));
- assert(NULL != pStack);
-
- memset(pStack, 0, sizeof(STACK));
- pStack->pData = pData;
- pStack->maxLen = len;
-
- if(NULL != pLock)
- pStack->hLock = pLock;
-
- return pStack;
- }
复制代码 (2) 添加数据- STATUS push(struct _STACK* pStack, void* pData, int size)
- {
- assert(NULL != pStack && NULL != pData);
-
- if(NULL != pStack->hLock)
- WaitForSingleObject((HANDLE)pStack->hLock, INFINITE);
-
- if(pStack->top == pStack->maxLen){
- if(NULL != pStack->hLock)
- ReleaseMutex((HANDLE)pStack->hLock);
-
- return ERROR;
- }
-
- memmove((char*)pStack->pData + size * pStack->top, (char*)pData, size);
- pStack->top ++;
-
- if(NULL != pStack->hLock)
- ReleaseMutex((HANDLE)pStack->hLock);
-
- return OK;
- }
复制代码 (3) 对2进行优化,因为判断的条件比较复杂- #define STACK_CHECK_LOCK(hLock) \
- do{\
- if(hLock)\
- WaitForSingleObject((HANDLE)hLock, INFINITE);\
- }while(0)
-
- #define STACK_CHECK_UNLOCK(hLock) \
- do{\
- if(hLock)\
- ReleaseMutex((HANDLE)hLock);\
- }while(0)
复制代码 所以,2的代码可以修改为,- STATUS push(struct _STACK* pStack, void* pData, int size)
- {
- assert(NULL != pStack && NULL != pData);
-
- STACK_CHECK_LOCK(pStack->hLock);
-
- if(pStack->top == pStack->maxLen){
- STACK_CHECK_UNLOCK(pStack->hLock);
- return ERROR;
- }
-
- memmove((char*)pStack->pData + size * pStack->top, (char*)pData, size);
- pStack->top ++;
-
- STACK_CHECK_UNLOCK(pStack->hLock);
- return OK;
- }
复制代码 总结:
(1) 一般来说,比较好的数据结构要兼有多线程和没有多线程两种情况
(2) 如果需要用其他的锁代替mutex,直接换掉就可以,十分方便
|
|