Linux系统多线程编程基础

Linux系统下多线程编程可以采用glibc库中的POSIX库,glibc是Linux下的GUN C的函数库,其中包含了标准C库以及POSIX库。这部分内容参见Linux多线程基础

Windows多线程编程基础

待续

C++多线程编程基础

c++11/14/17提供了很多新特性,使用这部分新特性方便编写跨平台的程序。这部分内容参见C++11多线程基础

实例

学习完以上内容,不妨做几道练习

1.子线程打开一个文件,将系统当前时间写入。主线程读取文件中的时间并显示在屏幕上
  1. 使用POSIX库中的函数
#include <stdio.h>
#include <pthread.h>
#include <string.h>

#define FILE_NAME "time.txt"

void* write_time(void* arg) {
	time_t now = time(NULL);
	tm* time = localtime(&now);
	printf("%04d/%02d/%02d %02d:%02d:%02d\n", time->tm_year + 1900, 
			time->tm_mon + 1, 
			time->tm_mday,
			time->tm_hour,
			time->tm_min,
			time->tm_sec);

	char data[32] = {0};
	snprintf(data, sizeof(data), "%04d/%02d/%02d %02d:%02d:%02d",
			time->tm_year + 1900, 
			time->tm_mon + 1, 
			time->tm_mday,
			time->tm_hour,
			time->tm_min,
			time->tm_sec);
	
	FILE* filep = fopen(FILE_NAME, "w");
	if (!filep) pthread_exit(NULL);
	size_t length = strlen(data) + 1;
	size_t ret = fwrite(data, 1, length, filep);
	if (ret != length) {
		perror("fwrite()error\n");
	}
	fclose(filep);
	pthread_exit(NULL);
}	

int main() {
	pthread_t tid;
	if (pthread_create(&tid, NULL, write_time, NULL) != 0) {
		perror("pthread_create()error\n");
		return -1;
	}
	pthread_join(tid, NULL);

	FILE* filep = fopen(FILE_NAME, "r");
	if (!filep) perror("open file error\n");

	char data[32] = {0};
	size_t read_len = fread(data, 1, 32, filep);
	if (read_len == 0) {
		perror("fread()error\n");
		fclose(filep);
	}
	printf("current time is:%s\n", data);
	fclose(filep);

	return 0;
}
  1. 使用C++11中的thread类相关操作
#include <thread>
#include <iostream>
#include <string.h>

#define FILE_NAME "time.txt"

void write_time() {
	time_t now = time(nullptr);
	tm* time = localtime(&now);
	char data[32] = {0};
	snprintf(data, sizeof(data), "%04d/%02d/%02d %02d:%02d:%02d",
			time->tm_year + 1900, 
			time->tm_mon + 1, 
			time->tm_mday,
			time->tm_hour,
			time->tm_min,
			time->tm_sec);
	
	FILE* filep = fopen(FILE_NAME, "w");
	if (!filep) return;
	size_t length = strlen(data) + 1;
	size_t ret = fwrite(data, 1, length, filep);
	if (ret != length) {
		std::cout << "fwrite()error" << std::endl;
	}
	fclose(filep);
}

int main() {
	std::thread t(write_time);
	if (t.joinable()) t.join();

	FILE* filep = fopen(FILE_NAME, "r");
	if (!filep) std::cout << "open file error" << std::endl;

	char data[32] = {0};
	size_t read_len = fread(data, 1, 32, filep);
	if (read_len == 0) {
		std::cout << "fread()error\n" << std::endl;
		fclose(filep);
	}
	std::cout << "current time is:" <<  data << std::endl;
	fclose(filep);

	return 0;
}
2.实现多生产者多消费者模型
  1. 条件变量结合互斥锁
  2. 信号量
  3. 无锁队列