Linux系统下C/C++编程

参考视频

Linux下C/CPP开发基础

gcc库使用

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat main.cpp 
#include<iostream>
#include"mymath.h"
using namespace std;

int main(){
	int a=10;
	int b=20;
	int c=add(a, b);
	cout<<a<<"+"<<b<<"="<<c<<endl;
	return 0;
}
 
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat mymath.cpp 
#include"mymath.h"
int add(int a, int b)
{
	return a+b;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat mymath.h
int add(int a, int b);
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.cpp mymath.cpp -o main
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

静态链接库 .a

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ -c mymath.cpp -o mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ll mymath.o
-rw-r--r-- 1 root root 1240 Mar 26 19:33 mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ar rcs libmymath.a mymath.o
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ -c main.cpp -o main.o  # 编译
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.o -L . -l mymath -o main # 链接
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

动态链接库 .so

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ mymath.cpp -shared -o libmymath.so
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ main.o -L . -l mymath -o main
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
./main: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# echo "$(pwd)" >> .so: cannot open shared object file: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat 
-bash: root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp#: No such file or directory
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# echo "$(pwd)" >> /etc/ld.so.conf
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat /etc/ld.so.conf
include /etc/ld.so.conf.d/*.conf

/root/cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ldconfig
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30

jsoncpp

jsoncpp usage

#下载 jsoncpp 源码
git clone https://github.com/open-source-parsers/jsoncpp.git 
#进到目录
cd jsoncpp-master
#创建目录
mkdir -p build/release
#进到编译目录
cd build/release
#使用 cmake 进行编译
cmake -DCMAKE_BUILD_TYPE=release -DBUILD_STATIC_LIBS=ON \
-DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_INCLUDEDIR=include/jsoncpp \
-DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" ../..
#编译和安装
make && make install

examples

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_demo01.c
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_demo01.c
#include <iostream>
#include <string>
#include <jsoncpp/json/json.h>
 
int main()
{
    std::cout << "Hello World!" << std::endl;
 
    Json::Value root;
    Json::FastWriter fast;
 
    root["ModuleType"] = Json::Value(1);
    root["ModuleCode"] = Json::Value("China");
 
    std::cout<<fast.write(root)<<std::endl;
 
    Json::Value sub;
    sub["version"] = Json::Value("1.0");
    sub["city"] = Json::Value(root);
    fast.write(sub);
 
    std::cout<<sub.toStyledString()<<std::endl;
 
    return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_demo01.c -o demo01 -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./demo01 
Hello World!
{"ModuleCode":"China","ModuleType":1}

{
	"city" : 
	{
		"ModuleCode" : "China",
		"ModuleType" : 1
	},
	"version" : "1.0"
}

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_demo02.c
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_demo02.c 
#include <string>
#include <jsoncpp/json/json.h>
#include <iostream>
 
using namespace std;
 
void readJson() {
	std::string strValue = "{\"name\":\"json\",\"array\":[{\"cpp\":\"jsoncpp\"},{\"java\":\"jsoninjava\"},{\"php\":\"support\"}]}";
 
	Json::Reader reader;
	Json::Value value;
 
	if (reader.parse(strValue, value))
	{
		std::string out = value["name"].asString();
		std::cout << out << std::endl;
		const Json::Value arrayObj = value["array"];
		for (unsigned int i = 0; i < arrayObj.size(); i++)
		{
			if (!arrayObj[i].isMember("cpp")) 
				continue;
			out = arrayObj[i]["cpp"].asString();
			std::cout << out;
			if (i != (arrayObj.size() - 1))
				std::cout << std::endl;
		}
	}
}
 
void writeJson() {
 
	Json::Value root;
	Json::Value arrayObj;
	Json::Value item;
 
	item["cpp"] = "jsoncpp";
	item["java"] = "jsoninjava";
	item["php"] = "support";
	arrayObj.append(item);
 
	root["name"] = "json";
	root["array"] = arrayObj;
 
	root.toStyledString();
	std::string out = root.toStyledString();
	std::cout << out << std::endl;
}
 
int main(int argc, char** argv) {
	readJson();
	writeJson();
	return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_demo02.c -o demo02 -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./demo02 
json
jsoncpp
{
	"array" : 
	[
		{
			"cpp" : "jsoncpp",
			"java" : "jsoninjava",
			"php" : "support"
		}
	],
	"name" : "json"
}

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim jsoncpp_speed.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat jsoncpp_speed.cpp
/*
 * @Descripttion: 测试jsoncpp的使用方法和性能
 * @version: 1.0
 * @Author: Milo
 * @Date: 2020-06-05 15:14:40
 * @LastEditors: Milo
 * @LastEditTime: 2020-06-05 15:14:40
 */
#include <memory>
#include <sstream>
#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>
#include "jsoncpp/json/json.h"
#include "jsoncpp/json/value.h"
#include "jsoncpp/json/reader.h"
#include "jsoncpp/json/writer.h"
 
/*
 
{
  "name": "milo",
  "age": 80,
  "languages": ["C++", "C"],
  "phone": {
    "number": "186****3143",
    "type": "home"
  },
  "books":[
      {
          "name": "Linux kernel development",
          "price":7.7
      },
      {
          "name": "Linux server development",
          "price": 8.0
      }
  ]"vip":true,
  "address": null
}
 */
static uint64_t getNowTime()
{
    struct timeval tval;
    uint64_t nowTime;
 
    gettimeofday(&tval, NULL);
 
    nowTime = tval.tv_sec * 1000L + tval.tv_usec / 1000L;
    return nowTime;
}
 
std::string JsoncppEncodeNew()
{
    std::string jsonStr;
    // 一个value是可以包含多个键值对
    Json::Value root, languages, phone, book, books;
 
    // 姓名
    root["name"] = "milo";
    // 年龄
    root["age"] = 80;
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = 7.7;
    books[0] = book;    // 深拷贝
    book["name"] = "Linux server development";
    book["price"] = 8.0;
    books[1] = book;    // 深拷贝
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = "yageguoji";
 
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;
    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(root, &os);
    jsonStr = os.str();
 
    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}
 
std::string JsoncppEncodeOld()
{
    std::string jsonStr;
    Json::Value root, languages, phone, book, books;
 
    // 姓名
     root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = "yageguoji"; //;// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
 
    Json::FastWriter writer;
    jsonStr = writer.write(root);
 
    // std::cout << "Json:\n" << jsonStr << std::endl;
    return jsonStr;
}
 
// 不能返回引用
Json::Value JsoncppEncodeOldGet()
{
    Json::Value root;
    Json::Value languages, phone, book, books;
 
    // 姓名
    root["name"] = "milo";
    //root["name"] = Json::nullValue;
    // 年龄
    root["age"] =  80; 
 
    // 语言
    languages[0] = "C++";
    languages[1] = "Java";
    root["languages"] = languages;
 
    // 电话
    phone["number"] = "186****3143";
    phone["type"] = "home";
    root["phone"] = phone;
 
    // 书籍
    book["name"] = "Linux kernel development";
    book["price"] = (float)7.7;
    books[0] = book;
    book["name"] = "Linux server development";
    book["price"] = (float)8.0;
    books[1] = book;
    root["books"] = books;
 
    // 是否为vip
    root["vip"] = true;
 
    // address信息空null
    root["address"] = Json::nullValue; //"yageguoji";// Json::nullValue; // 如果是null,则要用自定义的Json::nullValue,不能用NULL
 
 
 
    std::cout << "JsoncppEncodeOldGet:\n"  << std::endl;
    return root;
}
 
void printJsoncpp(Json::Value &root)
{
    if(root["name"].isNull())
    {
        std::cout << "name null\n";
    }
    std::cout << "name: " << root["name"].asString() << std::endl;
    std::cout << "age: " << root["age"].asInt() << std::endl;
 
    Json::Value &languages = root["languages"];
    std::cout << "languages: ";
    for (uint32_t i = 0; i < languages.size(); ++i)
    {
        if (i != 0)
        {
            std::cout << ", ";
        }
        std::cout << languages[i].asString();
    }
    std::cout << std::endl;
 
    Json::Value &phone = root["phone"];
    std::cout << "phone number: " << phone["number"].asString() << ", type: " << phone["type"].asString() << std::endl;
 
    Json::Value &books = root["books"];
    for (uint32_t i = 0; i < books.size(); ++i)
    {
        Json::Value &book = books[i];
        std::cout << "book name: " << book["name"].asString() << ", price: " << book["price"].asFloat() << std::endl;
    }
    std::cout << "vip: " << root["vip"].asBool() << std::endl;
 
    if (!root["address"].isNull())
    {
        std::cout << "address: " << root["address"].asString() << std::endl;
    }
    else
    {
        std::cout << "address is null" << std::endl;
    }
}
 
bool JsoncppDecodeNew(const std::string &info)
{
    if (info.empty())
        return false;
 
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(info.c_str(), info.c_str() + info.length(), &root, &errs);
    if (!res || !errs.empty())
    {
        std::cout << "parseJson err. " << errs << std::endl;
        return false;
    }
    // printJsoncpp(root);
 
    return true;
}
 
bool JsoncppDecodeOld(const std::string &strJson)
{
    if (strJson.empty())
        return false;
 
    bool res;
 
    Json::Value root;
    Json::Reader jsonReader;
 
    res = jsonReader.parse(strJson, root);
    if (!res)
    {
        std::cout << "jsonReader.parse err. " << std::endl;
        return false;
    }
 
    // printJsoncpp(root);
 
    return true;
}
 
const char *strCjson = "{                 \
	\"name\":	\"milo\",         \
	\"age\":	80,                 \
	\"languages\":	[\"C++\", \"C\"],\
	\"phone\":	{                       \
		\"number\":	\"186****3143\",    \
		\"type\":	\"home\"            \
	},                                  \
	\"books\":	[{                         \
			\"name\":	\"Linux kernel development\",   \
			\"price\":	7.700000        \
		}, {                            \
			\"name\":	\"Linux server development\",   \
			\"price\":	8               \
		}],                             \
	\"vip\":	true,                   \
	\"address\":	null                \
}                                      \
";
#define TEST_COUNT 100000
int main()
{
    std::string jsonStrNew;
    std::string jsonStrOld;
 
    jsonStrNew = JsoncppEncodeNew();
    // JsoncppEncodeNew size: 337
    std::cout << "JsoncppEncodeNew size: " << jsonStrNew.size() << std::endl;
    std::cout << "JsoncppEncodeNew string: " << jsonStrNew << std::endl;
    JsoncppDecodeNew(jsonStrNew);
 
    jsonStrOld = JsoncppEncodeOld();
    // JsoncppEncodeOld size: 248
    std::cout << "\n\nJsoncppEncodeOld size: " << jsonStrOld.size() << std::endl;
    std::cout << "JsoncppEncodeOld string: " << jsonStrOld << std::endl;
    JsoncppDecodeOld(jsonStrOld);
 
    Json::Value root = JsoncppEncodeOldGet();
    Json::FastWriter writer;
    std::cout << "writer:\n"  << std::endl;
    std::string jsonStr = writer.write(root);
    std::cout << "\n\njsonStr string: " << jsonStrOld << std::endl;
#if 1
    uint64_t startTime;
    uint64_t nowTime;
    
    startTime = getNowTime();
    std::cout << "jsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeNew();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp encode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppEncodeOld();
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp encode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeNew(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
 
    startTime = getNowTime();
    std::cout << "\njsoncpp decode time testing" << std::endl;
    for(int i = 0; i < TEST_COUNT; i++)
    {
        JsoncppDecodeOld(jsonStrNew);
    }
    nowTime = getNowTime();
    std::cout << "jsoncpp decode " << TEST_COUNT << " time, need time: "
         << nowTime-startTime << "ms"  << std::endl;
#endif
 
    return 0;
}
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# g++ jsoncpp_speed.cpp -o jsoncpp_speed -ljsoncpp -std=c++11
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./jsoncpp_speed
JsoncppEncodeNew size: 345
JsoncppEncodeNew string: {
	"address" : "yageguoji",
	"age" : 80,
	"books" : 
	[
		{
			"name" : "Linux kernel development",
			"price" : 7.7000000000000002
		},
		{
			"name" : "Linux server development",
			"price" : 8.0
		}
	],
	"languages" : 
	[
		"C++",
		"Java"
	],
	"name" : "milo",
	"phone" : 
	{
		"number" : "186****3143",
		"type" : "home"
	},
	"vip" : true
}


JsoncppEncodeOld size: 253
JsoncppEncodeOld string: {"address":"yageguoji","age":80,"books":[{"name":"Linux kernel development","price":7.6999998092651367},{"name":"Linux server development","price":8.0}],"languages":["C++","Java"],"name":"milo","phone":{"number":"186****3143","type":"home"},"vip":true}

JsoncppEncodeOldGet:

writer:



jsonStr string: {"address":"yageguoji","age":80,"books":[{"name":"Linux kernel development","price":7.6999998092651367},{"name":"Linux server development","price":8.0}],"languages":["C++","Java"],"name":"milo","phone":{"number":"186****3143","type":"home"},"vip":true}

jsoncpp encode time testing
jsoncpp encode 100000 time, need time: 1435ms

jsoncpp encode time testing
jsoncpp encode 100000 time, need time: 789ms

jsoncpp decode time testing
jsoncpp decode 100000 time, need time: 988ms

jsoncpp decode time testing
jsoncpp decode 100000 time, need time: 643ms

视频中
main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include "json.h"
using namespace std;
int main() {
	ifstream scriptFile;
	string name = "./test.json";
	scriptFile.open(name);
	if (!scriptFile.is_open())
	{
		cout << "File" << name << " does not exist!" << endl;
		return 0;
	}
	Json::CharReaderBuilder builder;
	builder["collectComments"] = true;
	JSONCPP_STRING errs;
	Json::Value root;
	if (!parseFromStream(builder scriptFile, &root, &errs) {
		cout << "Wrong in paser from json file" << endl;
			throw runtime_error("");
	}
	auto str=root.toStyledString();
	cout<<str<<endl;
	return 0;
}

在这里插入图片描述
在这里插入图片描述

makefile

makefile

root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# make
g++ -o main mymath.cpp main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# vim makefile 
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# make clean && make
rm -f main
g++ -o main mymath.cpp main.cpp
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# ./main 
10+20=30
root@iZuf6ir9zx8jfk2vinfpllZ:~/cpp# cat makefile 
cpp=$(wildcard *.cpp)
obj=main
$(obj):$(cpp)
	g++ -o $@ $^
.PHONY: clean
clean:
	rm -f $(obj)

cmake

CMake 良心教程,教你从入门到入魂 - 程序员阿德的文章 - 知乎

# 目录下有CMakeLists.txt
cmake .
# 生成makefile文件
make
# 自动编译

example

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)
  
# set the project name
project(Tutorial LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# add the executable
add_executable(${PROJECT_NAME} tutorial.cpp)

tutorial.cpp

#include <cmath>
#include <cstdlib>
#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
    if (argc < 2) {
        std::cout << "Usage: " << argv[0] << " number" << std::endl;
        return 1;
    }

    // convert input to double
    const double inputValue = atof(argv[1]);

    // calculate square root
    const double outputValue = sqrt(inputValue);
    std::cout << "The square root of " << inputValue
              << " is " << outputValue
              << std::endl;
    return 0;
}

在这里插入图片描述
视频
视频
cmake 用于 jsoncpp/example

 cd ..
 g++ ./stringWrite/stringWrite.cpp -ljsoncpp -std=c++11 -o stringWrite
 g++ ./stringWrite/stringWrite.cpp -ljsoncpp -std=c++11 -o ./stringWrite/stringWrite.o
 ./stringWrite/stringWrite.o
 g++ ./streamWrite/streamWrite.cpp -ljsoncpp -std=c++11 -o ./streamWrite/streamWrite.o
 vim ./streamWrite/streamWrite.cpp
 cat ./streamWrite/streamWrite.cpp
 g++ ./streamWrite/streamWrite.cpp -ljsoncpp -std=c++11 -o ./streamWrite/streamWrite.o
 ./streamWrite/streamWrite.o
 cat ./readFromString/readFromString.cpp 

在这里插入图片描述

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
这是一门linuxc++通讯架构实战课程,针对c/c++语言已经掌握的很熟并希望进一步深造以将来用c++linux下从事网络通讯领域/网络服务器的开发和架构工作。这门课程学习难度颇高但也有着极其优渥的薪水(最少30K月薪,最高可达60-80K月薪),这门课程,会先从nginx源码的分析和讲解开始,逐步开始书写属于自己的高性能服务器框架代码,完善个人代码库,这些,将会是您日后能取得高薪的重要筹码。本课程原计划带着大家逐行写代码,但因为代码实在过于复杂和精细,带着写代码可能会造成每节课至少要4~5小时的超长时间,所以老师会在课前先写好代码,主要的时间花费在逐行讲解这些代码上,这一点望同学们周知。如果你觉得非要老师领着写代码才行的话,老师会觉得你当前可能学习本门课程会比较吃力,请不要购买本课程,以免听不懂课程并给老师差评,差评也会非常影响老师课程的销售并造成其他同学的误解。 这门课程要求您具备下面的技能:(1)对c/c++语言掌握的非常熟练,语言本身已经不是继续学习的障碍,并不要求您一定熟悉网络或者linux;(2)对网络通讯架构领域有兴趣、勇于挑战这个高难度的开发领域并期望用大量的付出换取高薪;在这门课程中,实现了一个完整的项目,其中包括通讯框架和业务逻辑框架,浓缩总结起来包括如下几点:(1)项目本身是一个极完整的多线程高并发的服务器程序;(2)按照包头包体格式正确的接收客户端发送过来的数据包, 完美解决收包时的数据粘包问题;(3)根据收到的包的不同来执行不同的业务处理逻辑;(4)把业务处理产生的结果数据包正确返回给客户端;本项目用到的主要开发技术和特色包括:(1)epoll高并发通讯技术,用到的触发模式是epoll中的水平触发模式【LT】;(2)自己写了一套线程池来处理业务逻辑,调用适当的业务逻辑处理函数处理业务并返回给客户端处理结果;(3)线程之间的同步技术包括互斥量,信号量等等;(4)连接池中连接的延迟回收技术,这是整个项目中的精华技术,极大程度上消除诸多导致服务器程序工作不稳定的因素;(5)专门处理数据发送的一整套数据发送逻辑以及对应的发送线程;(6)其他次要技术,包括信号、日志打印、fork()子进程、守护进程等等;
### 回答1: Linux下的多线程编程可以使用C/C++语言实现。C/C++语言提供了一些多线程编程的库,如pthread库、OpenMP库、Boost库等。其中,pthread库是Linux下最常用的多线程编程库,它提供了一系列的API函数,可以用来创建、管理和同步线程。在C/C++语言中,可以使用pthread_create()函数创建线程,使用pthread_join()函数等待线程结束,使用pthread_mutex_lock()和pthread_mutex_unlock()函数实现线程间的互斥访问等。同时,C++11标准也提供了一些多线程编程的支持,如std::thread类、std::mutex类等,可以方便地实现多线程编程。 ### 回答2: Linux下的多线程编程是指在Linux系统下使用多个线程来执行不同的任务,从而提高程序的运行效率和响应速度。 C/C++Linux下最常用的编程语言之一,也是多线程编程的主要语言。实现多线程编程可以使用线程库,其中最常用的是pthread库。 Pthread库是Linux下的开放式多线程库,它允许程序员使用标准的POSIX线程接口来创建、终止、同步和管理线程。使用Pthread库可以很方便地进行多线程编程,其中主要包括以下几个方面。 1. 创建和启动线程:使用pthread_create函数来创建和启动线程,该函数需要传递线程ID、线程属性和线程函数等参数。 2. 同步线程:使用pthread_join函数来等待一个线程结束,以便获取线程的返回值。使用pthread_mutex和pthread_cond等函数来进行线程同步。 3. 线程控制:使用pthread_cancel函数来取消线程,使用pthread_exit函数来终止线程。 4. 共享变量:在多个线程之间共享变量时,需要使用pthread_mutex和pthread_cond等函数来控制并发访问。 在进行多线程编程时,需要注意一些问题,如线程安全、死锁等问题。不同的线程对共享资源的读写需要使用同步机制,避免竞争和冲突。此外,要注意避免死锁,即多个线程互相等待对方释放资源,造成程序无法正常运行。 总之,Linux下的多线程编程是一项非常重要的技术,在实际开发中应用广泛。使用C/C++编写多线程程序,需要熟悉线程库的使用方法,掌握线程的创建、同步、控制和共享等技术,以保证程序的稳定性和运行效率。 ### 回答3: Linux是一种开源的操作系统,其多线程编程能力是其强大之处之一。当我们需要编写一个高性能、高并发的程序时,多线程编程无疑会是一个很好的选择。 在Linux下,C/C++是最常用的编程语言之一,也是多线程编程的重要语言之一。在C/C++中编写多线程程序主要依赖于pthread库。pthread库提供了一套多线程API,可以很方便的创建和管理线程。 使用pthread库创建线程需要以下步骤: 1. 包含pthread库头文件: #include <pthread.h> 2. 定义线程函数: void *thread_func(void *arg){ //线程执行的代码 } 3. 创建线程: pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); 4. 等待线程结束: pthread_join(tid, NULL); 以上代码片段就创建了一个新线程,并在新线程中执行了thread_func函数。pthread_create函数的第一个参数为线程ID,第二个参数为线程属性,一般使用NULL,第三个参数为线程函数,第四个参数为线程函数的参数。 多线程编程需要注意以下几点: 1. 线程安全:多个线程同时操作同一个共享资源,需要确保操作的正确性和安全性。 2. 线程同步:使用锁、互斥量等机制保证线程之间的同步。 3. 线程调度:多个线程之间需要进行调度,需要注意线程优先级的设置。 总之,在Linux下使用C/C++进行多线程编程是一项非常有用的技能。在实际开发中,需要结合具体的场景和需求,通过选择合适的多线程编程模型、算法和数据结构来实现高效、高性能的程序。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值