欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

多线程共享数据

程序员文章站 2024-02-09 17:52:58
...
#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;
	q = pthread_getspecific(g_key);
	if(q != NULL)
	{
		printf("\033[32m[%s:%d]\033[36m release_buffer must be called somewhere\033[0m\n", __FUNCTION__, __LINE__);
		return;
	}
	if(p == NULL || size <= 0)
	{
		printf("\033[32m[%s:%d]\033[36m %p, %d\033[0m\n", __FUNCTION__, __LINE__, p, size);
		return ;
	}
	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;
}