Skip to content

Commit 62e4cf4

Browse files
committed
tones of updates
1 parent 3202879 commit 62e4cf4

13 files changed

+1077
-295
lines changed

CMakeLists.txt

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ message("CMAKE_CXX_COMPILER_VERSION: " ${CMAKE_CXX_COMPILER_VERSION})
2424

2525
add_executable(pointers src/pointers/pointers.cpp)
2626

27-
#add_executable(string src/string.cpp )
27+
add_executable(string src/string.cpp )
2828

2929
add_executable(exception_handling src/exception_handling.cpp)
3030

@@ -280,6 +280,7 @@ add_executable(circular_dependency src/class/circular_dependency/circular_depend
280280

281281
add_executable(core_dump src/core_dump.cpp)
282282

283+
#add_executable(packaged_task src/packaged_task.cpp)
283284

284285
if(${CMAKE_GNU_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} GREATER_EQUAL 13)
285286
add_executable(printing_with_format src/printing_with_format.cpp)
@@ -353,6 +354,7 @@ if(testing_enabled)
353354
endif()
354355

355356

357+
option(SANITIZE "Add sanitizer flags" OFF)
356358

357359

358360
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
@@ -362,18 +364,21 @@ if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
362364

363365
add_executable(align src/align.cpp)
364366

365-
366-
set(CMAKE_CXX_FLAGS "-fsanitize=address ${CMAKE_CXX_FLAGS}")
367-
set(CMAKE_CXX_FLAGS "-fno-omit-frame-pointer ${CMAKE_CXX_FLAGS}")
368367
add_executable(signals src/signals.cpp)
369368
add_executable(system_call src/system_call.cpp)
370369

371370
# add_executable(date_time src/date_time.cpp)
372-
373371
add_executable(fork src/fork.cpp)
374372

375373
endif()
376374

375+
if(SANITIZE)
376+
set(CMAKE_CXX_FLAGS "-fsanitize=address ${CMAKE_CXX_FLAGS}")
377+
set(CMAKE_CXX_FLAGS "-fno-omit-frame-pointer ${CMAKE_CXX_FLAGS}")
378+
endif(SANITIZE)
379+
380+
381+
377382
add_executable(any src/any.cpp)
378383

379384

README.md

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,23 @@ This change ensures that VSCode uses the "Ninja Multi-Config" generator by defau
137137
* [Assert](docs/assert.md)
138138
* [Atomic operations and Atomic Types](docs/atomic.md)
139139
* [Asynchronous programming](docs/asynchronous_programming.md)
140+
- [std::launch::async, std::future](docs/asynchronous_programming.md#std--launch--async--std--future)
141+
- [Parallelization with ascync](docs/asynchronous_programming.md#parallelization-with-ascync)
142+
- [Parallelization with std::packaged_task](docs/asynchronous_programming.md#parallelization-with-std--packaged-task)
140143
* [Attribute specifier sequence [[ attribute-list ]] ](docs/attribute_specifier_sequence.md)
141144
* [Basic IO Operation, Streams, Reading/Writing Files, Formatting Output, cin, scanf, gets, getline, printf](docs/basic_IO_operation.md)
142145
* [Bitset, Bit field, Bitwise Operations](docs/bitset_bit_field_bitwise_operations.md)
143-
* [Callbacks](docs/callbacks.md)
144-
* [Callable Objects, std::function, std::bind, Lambda](docs/callable_objects_function_bind_lambda.md)
146+
* [Callable Objects, Callbacks](docs/callable_callbacks.md)
147+
- [1. Function Pointers](docs/callable_callbacks.md#1-function-pointers)
148+
- [2. Functor (Function Objects)](docs/callable_callbacks.md#2-functor--function-objects-)
149+
- [3. std::function, std::placeholders, and std::bind](docs/callable_callbacks.md#3-std--function--std--placeholders--and-std--bind)
150+
- [4. Lambda Functions](docs/callable_callbacks.md#4-lambda-functions)
151+
- [5. Member Function Pointers](docs/callable_callbacks.md#5-member-function-pointers)
152+
- [6. Signals and Slots](docs/callable_callbacks.md#6-signals-and-slots)
153+
- [7. std::invoke](docs/callable_callbacks.md#7-std--invoke)
154+
- [8. Packaged Tasks](docs/callable_callbacks.md#8-packaged-tasks)
155+
- [9. Coroutines](docs/callable_callbacks.md#9-coroutines)
156+
- [10. Auto-generated operator() from a Captureless Lambda](docs/callable_callbacks.md#10-auto-generated-operator---from-a-captureless-lambda)
145157
* [Clock, Date, Time](docs/date_time.md)
146158
* [Conditional Compilation From CMakeLists](docs/conditional_compilation.md)
147159
* [Containers](docs/containers.md)
@@ -158,6 +170,7 @@ This change ensures that VSCode uses the "Ninja Multi-Config" generator by defau
158170
* [Dynamic Memory Allocation in C](docs/dynamic_memory_allocation.md)
159171
* [Enum](docs/enum.md)
160172
* [Error Handling](docs/error_handling.md)
173+
* [Error Code](docs/error_code.md)
161174
* [Exception Handling, noexcept](docs/exception_handling.md)
162175
* [Extern Variables, Extern Functions](docs/extern.md)
163176
* [File System](docs/filesystem.md)
@@ -166,7 +179,6 @@ This change ensures that VSCode uses the "Ninja Multi-Config" generator by defau
166179
* [Functions, Extern Function, Function Objects, Function Pointer, Inline Functions](docs/functions.md)
167180
* [Hash Functions, Hash Data Structure (Hash Table)](docs/hash_function_hash_table.md)
168181
* [Heap and Stack, Memory Layout of C Programs](docs/heap_and_stack_memory_layout_of_C_programs.md)
169-
* [Invoke](docs/std_invoke.md)
170182
* [Iterator, for_each loop, range-for loop, Loop optimization](docs/iterator_loop.md)
171183
* [Lambda](docs/lambda.md)
172184
* [Literals](docs/literals.md)
@@ -178,6 +190,7 @@ This change ensures that VSCode uses the "Ninja Multi-Config" generator by defau
178190
* [Numeral Systems in C++ Decimal, Binary, Octal, Hexadecimal](docs/numeral_system.md)
179191
* [Optional](docs/optional.md)
180192
* [Parameter Pack Expansion ...](docs/parameter_pack_expansion_(...).md)
193+
* [Packaged Task](docs/packaged_task.md)
181194
* [Register Keyword](docs/register.md)
182195
* [Regex](docs/regex.md)
183196
* [Pseudo-random Number Generation, Distributions](docs/random_number.md)

docs/asynchronous_programming.md

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
# Asynchronous Calls
12
In C++, asynchronous programming can be achieved using various mechanisms such as threads, `std::async`, `std::future`, and `std::promise`. One common way to create asynchronous calls is through `std::async` which runs a function asynchronously (potentially in a new thread) and returns a `std::future` that will hold the result of that function call once it completes.
23

4+
5+
## std::launch::async, std::future
36
Here is an example demonstrating an asynchronous call in C++ using `std::async`:
47

58
```c++
@@ -101,3 +104,118 @@ Explanation:
101104
- After the first lambda has finished its work and has waited for the second lambda, the main thread continues and waits for the first asynchronous task to complete by calling `work_future.get()`.
102105

103106
By capturing by value, we ensure that each lambda has its own independent copy of the parameters, which is usually the safest way to pass parameters to asynchronous calls to avoid any potential data races or undefined behavior due to accessing shared data from multiple threads.
107+
108+
109+
110+
111+
## Parallelization with ascync
112+
113+
114+
```cpp
115+
#include <iostream>
116+
#include <vector>
117+
#include <numeric>
118+
#include <future>
119+
#include <thread>
120+
#include <iterator>
121+
122+
// Function to sum a chunk of the vector
123+
template <typename Iterator>
124+
long long sum_chunk(Iterator begin, Iterator end) {
125+
return std::accumulate(begin, end, 0LL);
126+
}
127+
128+
int main() {
129+
// Example vector
130+
std::vector<int> vec(1000000, 1); // Vector of 1 million elements, each initialized to 1
131+
132+
// Determine the number of chunks based on hardware concurrency
133+
unsigned int num_chunks = std::thread::hardware_concurrency();
134+
if (num_chunks == 0) num_chunks = 2; // Fallback in case hardware_concurrency returns 0
135+
136+
std::vector<std::future<long long>> futures;
137+
size_t chunk_size = vec.size() / num_chunks;
138+
auto begin = vec.begin();
139+
140+
// Launch async tasks for each chunk
141+
for (unsigned int i = 0; i < num_chunks; ++i) {
142+
auto end = (i == num_chunks - 1) ? vec.end() : std::next(begin, chunk_size);
143+
futures.push_back(std::async(std::launch::async, sum_chunk<std::vector<int>::iterator>, begin, end));
144+
begin = end;
145+
}
146+
147+
// Collect the results from each chunk
148+
long long total_sum = 0;
149+
for (auto& future : futures) {
150+
total_sum += future.get();
151+
}
152+
153+
std::cout << "Total sum: " << total_sum << std::endl;
154+
155+
return 0;
156+
}
157+
```
158+
159+
160+
## Parallelization with std::packaged_task
161+
162+
```cpp
163+
#include <iostream>
164+
#include <vector>
165+
#include <numeric>
166+
#include <thread>
167+
#include <future>
168+
#include <iterator>
169+
#include <functional>
170+
171+
// Function to sum a chunk of the vector
172+
template <typename Iterator>
173+
long long sum_chunk(Iterator begin, Iterator end) {
174+
return std::accumulate(begin, end, 0LL);
175+
}
176+
177+
int main() {
178+
// Example vector
179+
std::vector<int> vec(1000000, 1); // Vector of 1 million elements, each initialized to 1
180+
181+
// Determine the number of chunks based on hardware concurrency
182+
unsigned int num_chunks = std::thread::hardware_concurrency();
183+
if (num_chunks == 0) num_chunks = 2; // Fallback in case hardware_concurrency returns 0
184+
185+
std::vector<std::future<long long>> futures;
186+
std::vector<std::thread> threads;
187+
size_t chunk_size = vec.size() / num_chunks;
188+
auto begin = vec.begin();
189+
190+
// Launch tasks for each chunk using std::packaged_task
191+
for (unsigned int i = 0; i < num_chunks; ++i) {
192+
auto end = (i == num_chunks - 1) ? vec.end() : std::next(begin, chunk_size);
193+
194+
std::packaged_task<long long(std::vector<int>::iterator, std::vector<int>::iterator)> task(sum_chunk<std::vector<int>::iterator>);
195+
futures.push_back(task.get_future());
196+
197+
// Move the task to a new thread and execute it
198+
threads.emplace_back(std::move(task), begin, end);
199+
200+
begin = end;
201+
}
202+
203+
// Collect the results from each chunk
204+
long long total_sum = 0;
205+
for (auto& future : futures) {
206+
total_sum += future.get();
207+
}
208+
209+
// Join all threads
210+
for (auto& thread : threads) {
211+
thread.join();
212+
}
213+
214+
std::cout << "Total sum: " << total_sum << std::endl;
215+
216+
return 0;
217+
}
218+
219+
```
220+
221+

0 commit comments

Comments
 (0)