Process Thread Fiber (windows+linux+STL)
OS: windows
PS. include Fiber
Function Description
ConvertFiberToThread Converts the current fiber into a thread.
ConvertThreadToFiber Converts the current thread into a fiber.
ConvertThreadToFiberEx Converts the current thread into a fiber.
CreateFiber Allocates a fiber object, assigns it a stack, and sets up execution to begin at the specified start address.
CreateFiberEx Allocates a fiber object, assigns it a stack, and sets up execution to begin at the specified start address.
DeleteFiber Deletes an existing fiber.
FiberProc An application-defined function used with the CreateFiber function.
FlsAlloc Allocates a fiber local storage (FLS) index.
FlsFree Releases an FLS index.
FlsGetValue Retrieves the value in the calling fiber's FLS slot for a specified FLS index.
FlsSetValue Stores a value in the calling fiber's FLS slot for a specified FLS index.
IsThreadAFiber Determines whether the current thread is a fiber.
SwitchToFiber Schedules a fiber.
- [CreateThread](https://technet.microsoft.com/zh-cn/interopmigration/ms682453%28v=vs.80%29)
https://technet.microsoft.com/zh-cn/interopmigration/ms682516%28v=vs.80%29
- [_beginthread, _beginthreadex](http://technet.microsoft.com/zh-cn/library/kdzttdcb%28v=vs.110%29)
[_endthread, _endthreadex](http://technet.microsoft.com/zh-cn/library/hw264s73%28v=vs.110%29)
- 设置优先级,就是CPU的优先级
[GetThreadPriority](https://technet.microsoft.com/zh-cn/interopmigration/ms683235(v=vs.80))
[SetThreadPriority](https://technet.microsoft.com/zh-cn/interopmigration/ms686277(v=vs.80))
WaitForSingleObject
WaitForMultipleObjects
关于该用哪个函数 创建线程,下面已经详细解释了
windows 核心编程 6.4章 有说过
CreateThread
函数是用来创建线程的Windows函数。
不过,如果你正在编写C/C++代码,决不应该调用CreateThread
。相反,应该使用 Visual C++运行期库函数_beginthreadex
。
如果不使用Microsoft的Visual C++编译器,你的编译器供应商有它自己的替代函数。
不管这个替代函数是什么,你都必须使用。本章后面将要介绍_beginthreadex
能够做什么,它的重要性何在。
这就是Create Thread函数的概述,下面各节将要具体介绍Createthread
的每个参数。
https://technet.microsoft.com/zh-cn/interopmigration/ms682516(v=vs.80)
The MyThreadFunction function avoids the use of the C run-time library (CRT), as many of its functions are not thread-safe, particularly if you are not using the multithreaded CRT. If you would like to use the CRT in a ThreadProc function, use the _beginthreadex function instead.
https://technet.microsoft.com/zh-cn/interopmigration/ms682453(v=vs.80)
A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multithreaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
总结下:
如果使用Createthread调用了C run-time library (CRT) 会有问题
- CRT中函数 非线程安全(多线程场合) -----原因的话,可能和static有关 gethostbyname
- CRT会导致系统low-memory时,会terminate进程。
所以推荐使用 _beginthreadex
and _endthreadex
来替代。
Thread Safety in the C++ Standard Library
demo传送门:
windows thread 多线程之只利用event顺序执行各个线程
Each new thread or fiber receives its own stack space consisting of both reserved and initially committed memory. The reserved memory size represents the total stack allocation in virtual memory. As such, the reserved size is limited to the virtual address range. The initially committed pages do not utilize physical memory until they are referenced; however, they do remove pages from the system total commit limit, which is the size of the page file plus the size of the physical memory. The system commits additional pages from the reserved stack memory as they are needed, until either the stack reaches the reserved size minus one page (which is used as a guard page to prevent stack overflow) or the system is so low on memory that the operation fails.
It is best to choose as small a stack size as possible and commit the stack that is needed for the thread or fiber to run reliably. Every page that is reserved for the stack cannot be used for any other purpose.
A stack is freed when its thread exits. It is not freed if the thread is terminated by another thread.
The default size for the reserved and initially committed stack memory is specified in the executable file header. Thread or fiber creation fails if there is not enough memory to reserve or commit the number of bytes requested. The default stack reservation size used by the linker is 1 MB. To specify a different default stack reservation size for all threads and fibers, use the STACKSIZE statement in the module definition (.def) file. The operating system rounds up the specified size to the nearest multiple of the system's allocation granularity (typically 64 KB). To retrieve the allocation granularity of the current system, use the GetSystemInfo function.
To change the initially committed stack space, use the dwStackSize parameter of the CreateThread, CreateRemoteThread, or CreateFiber function. This value is rounded up to the nearest page. Generally, the reserve size is the default reserve size specified in the executable header. However, if the initially committed size specified by dwStackSize is larger than or equal to the default reserve size, the reserve size is this new commit size rounded up to the nearest multiple of 1 MB.
To change the reserved stack size, set the dwCreationFlags parameter of CreateThread or CreateRemoteThread to STACK_SIZE_PARAM_IS_A_RESERVATION and use the dwStackSize parameter. In this case, the initially committed size is the default size specified in the executable header. For fibers, use the dwStackReserveSize parameter of CreateFiberEx. The committed size is specified in the dwStackCommitSize parameter.
The SetThreadStackGuarantee function sets the minimum size of the stack associated with the calling thread or fiber that will be available during any stack overflow exceptions.
Thread Local Storage
Thread Local Storage (Visual C++)
Using Thread Local Storage
Using Thread Local Storage in a Dynamic Link Library
OS: linux
process thread Fiber(linux) 传送门
thread
http://www.cplusplus.com/reference/thread/thread/
http://en.cppreference.com/w/cpp/thread/thread
// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void funA()
{
// do stuff...
int i = 0;
while (i < 500) {
printf_s("i =%d , this is funA========== \n",i++);
}
}
void funB(int x)
{
// do stuff...
int i = 0;
while (i < 500) {
printf_s("i =%d , this is funB \n", i++);
}
}
int main()
{
//thread example
std::thread first(funA); // spawn new thread that calls funA()
std::thread second(funB, 0); // spawn new thread that calls funB(0)
std::cout << "main, funA and funB now execute concurrently...\n";
// synchronize threads:
first.join(); // pauses until first finishes
second.join(); // pauses until second finishes
/*
//detach thread:
first.detach();
second.detach();
*/
std::cout << "funA and funB completed.\n";
}
thread对象并不会自动管理线程结束,需要手动控制。
常见的控制手段有两个:join和detach。
join 用于等待线程结束.
detach 用于托管线程,线程仍然继续运行至结束,但不再受到thread对象控制。
mutex
condition_variable
Member functions
(constructor) Construct condition_variable (public member function )
(destructor) Destroy condition_variable (public member function )
Wait functions
wait Wait until notified (public member function )
wait_for Wait for timeout or until notified (public member function )
wait_until Wait until notified or time point (public member function )
Notify functions
notify_one Notify one (public member function )
notify_all Notify all (public member function )
```cpp
// condition_variable example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void print_id (int id) {
std::unique_lock<std::mutex> lck(mtx);
while (!ready) cv.wait(lck);
// ...
std::cout << "thread " << id << '\n';
}
void go() {
std::unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_id,i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto& th : threads) th.join();
return 0;
}
Atomic
Atomic types are types that encapsulate a value whose access is guaranteed to not cause data races and can be used to synchronize memory accesses among different threads.
This header declares two C++ classes, atomic and atomic_flag, that implement all the features of atomic types in self-contained classes. The header also declares an entire set of C-style types and functions compatible with the atomic support in C.