[ Previous ] [ Contents ] [ Index ] [ Next ]

Ns_AllocThreadLocalStorage

Overview

Initialize a local thread storage variable.

Syntax

    int Ns_AllocThreadLocalStorage(
    	Ns_ThreadLocalStorage * tls, 
    	void (*destructor) (void *)
    );

Description

Initializes a thread local storage variable and sets its destructor function. The tls's value is initially NULL in all existing threads and any new threads which are later created. If the destructor function pointer is non-null and the tls is non-null in a particular thread when it exits, the destructor will be called for that thread.

Thread local storage is often used to store data which must be shared between unrelated functions much like global variables are used in a single threaded program. Thread local storage is also often used to provide buffer space unique to each thread when making older code thread safe.

Example

    static Ns_ThreadLocalStorage tls;
    
    void
    Init(void)
    {
    	/* This function is called once at startup. */
    	Ns_AllocThreadLocalStorage(&tls, Ns_Free);
    }
    
    char *
    GetBuffer
    {
    	void *ptr;
    
    	Ns_GetThreadLocalStorage(&tls, &ptr);
    	if (ptr == NULL) {
    		/* Allocate a buffer for this thread. */
    		ptr = Ns_Malloc(BUFFER_SIZE);
    		Ns_SetThreadLocalStorage(&tls, ptr);
    	}
    	return (char *) ptr;
    }

Top of Page

[ Previous ] [ Contents ] [ Index ] [ Next ]
Copyright © 1996 America Online, Inc.