CreateThread导è´å
åæ³é²çåå
è¿å¾ä»Cè¿è¡æ¶åºè¯´èµ·äºã
VCè¿è¡æ¶åºï¼æä¸ä¸ªå®errnoï¼ç¨æ¥è·å¾ä¸ä¸æ¥æä½çé误ç ï¼ç±»ä¼¼äºWin32ä¸çGetLastError()å½æ°ãå¨å¤çº¿ç¨ç¯å¢ä¸ï¼ä¸å线ç¨è°ç¨errnoè¿åçé½æ¯caller线ç¨çé误ç ï¼ç»å¯¹ä¸ä¼æ··æ·ï¼è¿æ¯å 为使ç¨äºTLSææ¯ã
TLSï¼Thread Local Storageï¼æ¯ç¨æ¥åå线ç¨ç¸å
³æ°æ®çä¸ç§ææ¯ï¼å¨Win32ä¸ç±æä½ç³»ç»çTls*ç³»åå½æ°æä¾æ¯æãä¾å¦ï¼å¯ä»¥å¨ç¨åºå¼å§çå°æ¹è°ç¨TlsAlloc()å½æ°ï¼è·å¾ä¸ä¸ªTLS indexï¼è¿ä¸ªindexå¨è¿ç¨èå´å
ææï¼ç¶åå¯ä»¥å建n个线ç¨ï¼å¨æ¯ä¸ªçº¿ç¨ä¸ä½¿ç¨TlsSetValue(index,data)å°çº¿ç¨ç¸å
³æ°æ®åindexå
³èèµ·æ¥ï¼ä½¿ç¨TlsGetValue(index)æ¥è·åå½å线ç¨åindexç¸å
³èçç线ç¨ç¸å
³æ°æ®ã
æ¥çmsdnå¯ä»¥åç°ï¼Tls*å½æ°çå®ä¹å¦ä¸ï¼
[cpp] view plaincopy
DWORD WINAPI TlsAlloc(void);
BOOL WINAPI TlsSetValue(
__in DWORD dwTlsIndex,
__in LPVOID lpTlsValue
);
LPVOID WINAPI TlsGetValue(
__in DWORD dwTlsIndex
);
BOOL WINAPI TlsFree(
__in DWORD dwTlsIndex
);
è§å¯TlsSetValue/TlsGetValueçååå¯ä»¥åç°ï¼ä¸indexå
³èçæ°æ®åªè½æ¯void *ç±»åï¼å æ¤é常çåæ³æ¯å¨çº¿ç¨å¼å§çæ¶åï¼ä¸ºè¿ä¸ªçº¿ç¨åé
ä¸åå
åï¼ç¨äºåå¨ææä¸çº¿ç¨ç¸å
³çæ°æ®ï¼ç¶åæè¿åå
åçèµ·å§å°åä¸indexå
³èèµ·æ¥ãå¦æè¿åå
åå¨çº¿ç¨éåºçæ¶å没æéæ¾æï¼é£å°±æå
åæ³é²çå±é©ã
åå°errnoï¼æ¥ççCè¿è¡æ¶åºæ¯å¦ä½å®ç°errnoçã
errnoç声æåå®ç°å¦ä¸ï¼
[c-sharp] view plaincopy
/* error.h - errnoç声æ */
_CRTIMP extern int * __cdecl _errno(void);
#define errno (*_errno())
/* dosmap.c - errnoçå®ç° */
int * __cdecl _errno(
void
)
{
_ptiddata ptd = _getptd_noexit();
if (!ptd) {
return &ErrnoNoMem;
} else {
return ( &ptd->_terrno );
}
}
è§å¯_errnoç代ç ï¼å½æ°é¦å
è°ç¨äº_getptd_noexit()å½æ°ï¼è¿ä¸ªå½æ°ç代ç å¦ä¸ï¼
[cpp] view plaincopy
/* tiddata.c - _getptd_noexit()å®ç° */
_ptiddata __cdecl _getptd_noexit (
void
)
{
_ptiddata ptd;
DWORD TL_LastError;
TL_LastError = GetLastError();
#ifdef _M_IX86
/*
* Initialize FlsGetValue function pointer in TLS by calling __set_flsgetvalue()
*/
if ( (ptd = (__set_flsgetvalue())(__flsindex)) == NULL ) {
#else /* _M_IX86 */
if ( (ptd = FLS_GETVALUE(__flsindex)) == NULL ) {
#endif /* _M_IX86 */
/*
* no per-thread data structure for this thread. try to create
* one.
*/
#ifdef _DEBUG
extern void * __cdecl _calloc_dbg_impl(size_t, size_t, int, const char *, int, int *);
if ((ptd = _calloc_dbg_impl(1, sizeof(struct _tiddata), _CRT_BLOCK, __FILE__, __LINE__, NULL)) != NULL) {
#else /* _DEBUG */
if ((ptd = _calloc_crt(1, sizeof(struct _tiddata))) != NULL) {
#endif /* _DEBUG */
if (FLS_SETVALUE(__flsindex, (LPVOID)ptd) ) {
/*
* Initialize of per-thread data
*/
_initptd(ptd,NULL);
ptd->_tid = GetCurrentThreadId();
ptd->_thandle = (uintptr_t)(-1);
}
else {
/*
* Return NULL to indicate failure
*/
_free_crt(ptd);
ptd = NULL;
}
}
}
SetLastError(TL_LastError);
return(ptd);
}
_getptd_noexit()å½æ°é¦å
éè¿TLSæ¥æ¾çº¿ç¨ç¸å
³æ°æ®ï¼å¦æ没ææ¾å°ï¼å°±åé
ä¸åå
åï¼åæ¾_tiddataç»æï¼å¹¶å°è¿åå
åä¸__flsindexç¸å
³èãç±æ¤å¯è§ï¼errnoç确使ç¨äºTLSææ¯ï¼èä¸éè¿æ¥æ¾_getptd_noexit() å¯ä»¥åç°ï¼VCè¿è¡æ¶åºä¸å¾å¤å¾å¤å½æ°é½ä½¿ç¨äºTLSï¼errnoåªä¸è¿æ¯å
¶ä¸çä¸ä¸ªå
¸åã
温馨提示:答案为网友推荐,仅供参考