重点集中在用多线程实现,建立线程特有数据,不会发生数据写入冲突。
实现的功能很简单,客户端连接成功后,输入一个整数,服务端返回它的二进制形式。客户端输入0,则主动退出。
三个文件:
duoxianc.c ,主文件
binarykey.c,线程执行函数及特有数据建立
client.c,客户端程序
基本概念:
int pthread_once(pthread_once_t *once_control, void (*init)(void));
一次性初始化函数,不管有多少个线程执行,只初始化一次。
int pthread_key_create(pthread_key_t *key, void (*destructor)(void *));
创建数据概念
int pthread_setspecific(pthread_key_t key, const void *value);
为数据概念分配内存
void *pthread_getspecific(pthread_key_t key);
查询为数据概念分配的内存
duoxianc.c
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <pthread.h