C++服务器开发
首先搭建VS2019的环境
因为在linux下运行,所以要将windows上与linux的端口和ip地址连接起来
要在项目属性中添加
完成后进入服务器开发,
线程和信号量的使用
边读边写
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
static sem_t sem;
static int flag = 0;
static char buff[32];
//线程函数格式
void* funmain(void* data)
{
while (true)
{
扫描二维码关注公众号,回复:
13550845 查看本文章
进入即线程阻塞
sem_wait(&sem);
printf("buff=%s", buff);
}
}
int main()
{
//定义一个线程
pthread_t pthreadid;
//初始化信号量
sem_init(&sem, 0, 0);
//主线程中调用函数,
pthread_create(&pthreadid, nullptr,funmain, nullptr);
while (true)
{
//每次读取一行。读取的数据保存在buf指向的字符数组中
fgets(buff, 1024, stdin);
//发射信号,给线程2
sem_post(&sem);
}
}