cpp11 implements thread pool (eight) - Linux platform compiles thread pool dynamic library

Experimental operation process

First use suthe command to switch the user to the root user,

Compile threadpool.cpp and threadpool.h into a dynamic library

jyhlinux@ubuntu:~/share/threadpool$ g++ -fPIC -shared threadpool.cpp -o libtdpool.so -std=c++17

Put the generated library and header files in the system directory , and delete the source files

root@ubuntu:/home/jyhlinux/share/threadpool# mv libtdpool.so /usr/local/lib/

root@ubuntu:/home/jyhlinux/share/threadpool# ls

test_threadpool.cpp threadpool.cpp threadpool.h

root@ubuntu:/home/jyhlinux/share/threadpool# rm threadpool.cpp

root@ubuntu:/home/jyhlinux/share/threadpool# mv threadpool.h /usr/local/include/

Compile and link to generate source files

root@ubuntu:/home/jyhlinux/share/threadpool# g++ test_threadpool.cpp -std=c++17 -ltdpool -lpthread

Executes the executable but fails because the runtime system looks for dynamic libraries in a different location

insert image description here

The runtime system /etc/ld.so.cachelooks for the dynamic library link in the file

insert image description here

Do the following to add configuration

root@ubuntu:/etc/ld.so.conf.d# vim /etc/ld.so.conf

Add a line /usr/local/lib

insert image description here

Then go back to the test file path and refresh the dynamic library configuration

jyhlinux@ubuntu:/etc/ld.so.conf.d$ cd ~/share/threadpool

jyhlinux@ubuntu:~/share/threadpool$ sudo ldconfig

Execute the program again, the program runs normally, and the garbled characters are encoding problems

some problems

Problem Description

If it is an old version of g++, there may be a deadlock phenomenon, because the condition_variabledestructor under g++ does not do anything, causing Semaphorethe class notifyto block:

void post()
{
    
    
	std::unique_lock<std::mutex> lock(mtx_);
	resLimit_++;
	cond_.notify_all();  // 阻塞在这里!!!
}

Threads can be debugged with gdb

gdb attach 进程号 #调试进程

info threads #查看进程中所有线程,前面有*代表当前线程

thread id #切换到info threads查看的线程id

bt #查看线程调用堆栈

Solution

You can add a value Semaphoreto the class to indicate whether it has exited. If you exit, do not perform lock and and operations. The modified class isboolwait notifySemaphore

class Semaphore
{
    
    
public:
	Semaphore(int limit = 0)
		:resLimit_(limit)
	{
    
    }
	~Semaphore() 
	{
    
    
		isExit_ = true;
	}
	void wait()
	{
    
    
		if(isExit_)	return ; //
		std::unique_lock<std::mutex> lock(mtx_);
		cond_.wait(lock, [&]()->bool {
    
     return resLimit_ > 0; }); // 
		resLimit_--;

	}
	void post()
	{
    
    
		if(isExit_)	return ;//
		std::unique_lock<std::mutex> lock(mtx_);
		resLimit_++;
		cond_.notify_all();
	}
private:
	std::atomic_bool isExit_;//
	int resLimit_;
	std::mutex mtx_;
	std::condition_variable cond_;
};

Guess you like

Origin blog.csdn.net/qq_42120843/article/details/130791925