天天看點

多線程共享資料

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

static pthread_key_t g_key = 0;
static pthread_once_t s_once = PTHREAD_ONCE_INIT;

void once_init()
{
	printf("\033[32m[%s:%d]\033[36m \033[0m\n", __FUNCTION__, __LINE__);
	pthread_key_create(&g_key, NULL);
}

void init_buffer()
{
	pthread_once(&s_once, once_init);
}

void set_buffer(void *p, int size)
{
	void *q = NULL;
	
	if(p == NULL || size <= 0)
	{
		printf("\033[32m[%s:%d]\033[36m %p, %d\033[0m\n", __FUNCTION__, __LINE__, p, size);
		return ;
	}
	
	q = pthread_getspecific(g_key);
	if(q != NULL)
	{
		free(q);
		q = NULL;
	}

	q = malloc(size + 1);
	memset(q, 0, size + 1);
	memcpy(q, p, size);
	pthread_setspecific(g_key, q);
}

void *get_buffer(void)
{
	return pthread_getspecific(g_key);
}

void release_buffer()
{
	void *q = NULL;
	q = pthread_getspecific(g_key);
	if(q != NULL)
		free(q);
}

void run(void *args)
{
	pthread_t pthread = pthread_self();
	char buffer[256];
	char *p = NULL;

	init_buffer();
	snprintf(buffer, sizeof(buffer), "test %lu", pthread);

	set_buffer(buffer, strlen(buffer));
	sleep(1);
	p = get_buffer();
	if(p)
		printf("\033[32m[%s:%d]\033[36m pthread = %lu %s\033[0m\n", __FUNCTION__, __LINE__, pthread, p);
	release_buffer();
}

int main(int argc, char *argv[])
{
	pthread_t thread1 = 0;
	pthread_t thread2 = 0;

	pthread_create(&thread1, NULL, (void *)run, NULL);
	pthread_create(&thread2, NULL, (void *)run, NULL);

	pthread_join(thread1, NULL);
	pthread_join(thread2, NULL);

	return 0;
}
           

繼續閱讀