[Concurrent parallel]_[c/c++]_[uses thread-local storage for threads locally Storage (TLS)-win32 and pthread comparison]

Source: Internet
Author: User


Scene:

1. You need to count the number of objects created on a thread.

2. When the heap space is created, it needs to be destroyed based on the thread needs to be created and ended.

3. Because the scope is that a thread can only see its own stored data, it does not require a critical section or mutex to maintain its own heap memory. Join if implemented with global STD::MAP, you must lock on put and get, which is a waste of resources.

4. Can be used to maintain a connection, such as a socket,database connection.


Description

1. Java also has its own thread-local storage threadlocal

2. Win32 version of Pthread: http://sourceware.org/pthreads-win32/


Example Test_tsl.cpp:

#include "stdafx.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <assert.h > #include <windows.h> #include "pthread.h" #define THREADCOUNT 4 DWORD dwtlsindex; VOID errorexit (const char*); static pthread_barrier_t barrier = null;static pthread_once_t random_is_initialized = pthread_once_init;static Pthread_ key_t key;  void Commonfunc (void) {LPVOID lpvdata;     Retrieve a data pointer for the current thread.    Lpvdata = TlsGetValue (Dwtlsindex);  if ((Lpvdata = = 0) && (GetLastError ()! = ERROR_SUCCESS)) errorexit ("TlsGetValue ERROR");    Use the data stored to the current thread.   int64_t* value = (int64_t*) lpvdata;     printf ("Common:thread%d:lpvdata=%lx:value=%lld\n", GetCurrentThreadID (), lpvdata,*value); Sleep (5000);  } DWORD WINAPI ThreadFunc (VOID) {lpvoid lpvdata;     Initialize the TLS index for this thread.    Lpvdata = (LPVOID) LocalAlloc (LPTR, 8); if (!  TlsSetValue (Dwtlsindex, Lpvdata))     Errorexit ("TlsSetValue error");   int64_t* value = (int64_t*) lpvdata;   *value = GetCurrentThreadID ();     printf ("Thread%d:lpvdata=%lx\n", GetCurrentThreadID (), lpvdata);  Commonfunc ();     Release the dynamic memory before the thread returns.    Lpvdata = TlsGetValue (Dwtlsindex);     if (Lpvdata! = 0) LocalFree ((hlocal) lpvdata); return 0;    }void Testwin32tls () {DWORD idthread;    HANDLE Hthread[threadcount];  int i;     Allocate a TLS index.   if (Dwtlsindex = TlsAlloc ()) = = tls_out_of_indexes) errorexit ("TlsAlloc failed"); 1.   Note that this dwtlsindex is not starting from 0.     printf ("Dwtlsindex%ld\n", dwtlsindex);//Create multiple threads.                            for (i = 0; i < ThreadCount; i++) {Hthread[i] = CreateThread (NULL,//default security attributes 0,          Use default stack size (lpthread_start_routine) ThreadFunc,//thread function             NULL,//no thread function argument 0,          Use default creation flags &idthread);       Returns thread identifier//Check the return value for success.    if (hthread[i] = = NULL) errorexit ("CreateThread error\n");     } for (i = 0; i < threadcount; i++) WaitForSingleObject (Hthread[i], INFINITE); TlsFree (Dwtlsindex);}   void Commonfuncpthread (void) {void* lpvdata = pthread_getspecific (key);   int64_t* value = (int64_t*) lpvdata; printf ("Common:thread%d:lpvdata=%lx:value=%lld\n", GetCurrentThreadID (), lpvdata,*value); }void* startpthread (void* data) {int64_t *buf = (int64_t*) malloc; *buf = GetCurrentThreadID ();p thread_setspecific ( Key, BUF);    Commonfuncpthread (); free (BUF); Pthread_barrier_wait (&barrier); return NULL;} 1. Call only once, can be placed at random a work thread execution function can, will randomly find a thread execution.//2. Dll_process_attach similar to Win32 is performed only once. void Testpthreadtls () { Pthread_key_create (&key, NULL);p thread_barrier_init (&barrier,null, ThreadCount + 1); for (int i = 0; i< ThreadcounT ++i) {pthread_t t;pthread_create (&t,null,startpthread,null);p Thread_detach (t);} 1. Wait for other threads to finish executing. pthread_barrier_wait (&barrier);p thread_key_delete (key);}   DWORD Main (VOID) {//1.win32tls printf ("testwin32tls\n");   Testwin32tls ();   1.pthread TLS printf ("testpthreadtls\n");   Testpthreadtls (); return 0;    } VOID errorexit (const char* lpszmessage) {fprintf (stderr, "%s\n", lpszmessage); ExitProcess (0); }


.

Output:

Testwin32tlsdwtlsindex 26thread 8452:lpvdata=714f50common:thread 8452:lpvdata=714f50:value=8452thread 8460:lpvdata =7153d0common:thread 8460:lpvdata=7153d0:value=8460thread 8456:lpvdata=715610common:thread 8456:lpvdata=715610:va Lue=8456thread 8464:lpvdata=715190common:thread 8464:lpvdata=715190:value=8464testpthreadtlscommon:thread 8520: Lpvdata=3b4eb0:value=8520common:thread 8512:lpvdata=3b4ff0:value=8512common:thread 8516:lpvdata=3b4eb0:value=851 6common:thread 8524:lpvdata=3b4ff0:value=8524

Reference:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms686749 (v=vs.85). aspx

https://msdn.microsoft.com/en-us/library/windows/desktop/ms686991 (v=vs.85). aspx

Http://blog.chinaunix.net/uid-10231348-id-3034751.html

http://blog.csdn.net/liulina603/article/details/17991731

Http://linux.die.net/man/3/pthread_once



[Concurrent parallel]_[c/c++]_[uses thread-local storage for threads locally Storage (TLS)-win32 and pthread comparison]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.