MCPcopy Create free account
hub / github.com/ChunelFeng/CThreadPool / tutorial_threadpool_3

Function tutorial_threadpool_3

tutorial.cpp:91–122  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

89
90
91void tutorial_threadpool_3(UThreadPoolPtr tp) {
92 /**
93 * 并发打印0~100之间的数字
94 * 使用commit和submit函数的区别,主要在于:
95 * 1,commit()属于非阻塞执行,是将线程函数执行的结果以future的类型返回,交由上层处理
96 * 2,submit()属于阻塞顺序执行,是在内部处理好超时等信息并作为结果返回,抛弃线程函数自身返回值
97 * 3,不需要线程函数返回值,并且不需要判断超时信息的场景,两者无区别(如下例)
98 */
99 const int size = 100;
100 CGRAPH_ECHO("thread pool task submit version : ");
101 for (int i = 0; i < size; i++) {
102 tp->submit([i] { std::cout << i << " "; }); // 可以看到,submit版本是有序执行的。如果需要想要无序执行,可以通过创建taskGroup的方式进行,或者使用commit方法
103 }
104 CGRAPH_SLEEP_SECOND(1) // 等待上面函数执行完毕,以便于观察结果。无实际意义
105 std::cout << "\r\n";
106
107 CGRAPH_ECHO("thread pool task group submit version : ");
108 UTaskGroup taskGroup;
109 for (int i = 0; i < size; i++) {
110 taskGroup.addTask([i] { std::cout << i << " "; }); // 将任务放到一个taskGroup中,并发执行。执行的结果是无序的
111 }
112 tp->submit(taskGroup);
113 CGRAPH_SLEEP_SECOND(1)
114 std::cout << "\r\n";
115
116 CGRAPH_ECHO("thread pool task commit version : ");
117 for (int i = 0; i < size; i++) {
118 tp->commit([i] { std::cout << i << " "; }); // commit版本,是无序执行的
119 }
120 CGRAPH_SLEEP_SECOND(1)
121 std::cout << "\r\n";
122}
123
124
125int main() {

Callers 1

mainFunction · 0.85

Calls 2

CGRAPH_ECHOFunction · 0.85
submitMethod · 0.80

Tested by

no test coverage detected