posix_playground: Added test for unique_ptrs.

This commit is contained in:
Michael Mueller
2022-08-10 16:33:35 +02:00
parent 304b61613b
commit 3e736fc888

View File

@@ -8,6 +8,9 @@
#include <vector> #include <vector>
#include <unistd.h> #include <unistd.h>
#include <iostream> #include <iostream>
#include <sys/mman.h>
#include <cstring>
#include <errno.h>
namespace Posix_playground { namespace Posix_playground {
class Chrono_thread; class Chrono_thread;
@@ -44,30 +47,32 @@ int main(void) {
std::cout << "Let's start some threads" << std::endl; std::cout << "Let's start some threads" << std::endl;
std::vector<Posix_playground::Chrono_thread*> thread_objs(5); std::unique_ptr<std::vector<Posix_playground::Chrono_thread*>> thread_objs = std::make_unique<std::vector<Posix_playground::Chrono_thread*>>();
std::vector<std::thread*> thread_list(4); std::vector<std::thread*> thread_list(4);
std::cout << "Let's use aligned memory for threads objects." << std::endl; std::cout << "Let's use aligned memory for threads objects." << std::endl;
for (int i = 0; i < 3; i++) { for (int i = 0; i < 3; i++) {
Posix_playground::Chrono_thread *thread_obj; Posix_playground::Chrono_thread *thread_obj = nullptr;
if(posix_memalign((void**)(&thread_obj), 64, sizeof(Posix_playground::Chrono_thread))) { // std::unique_ptr<Posix_playground::Chrono_thread> thread_obj;
if((posix_memalign((void**)&thread_obj, 64, sizeof(Posix_playground::Chrono_thread)))) {
std::cerr << "Could not allocate thread object " << i << std::endl; std::cerr << "Could not allocate thread object " << i << std::endl;
continue; continue;
} }
std::cout << "Thread object " << (i + 1) << " is at address " << (void *)(thread_obj) << std::endl; std::cout << "Thread object " << (i + 1) << " is at address " << (void *)(thread_obj) << std::endl;
thread_objs[i] = new (thread_obj) Posix_playground::Chrono_thread((std::uint16_t)(i+1)); thread_objs.get()->emplace_back(new (thread_obj) Posix_playground::Chrono_thread((std::uint16_t)(i+1)));
auto thread = new std::thread([thread_objs, i] auto thread = new std::thread([&thread_objs, i]
{ thread_objs[i]->execute(); }); { (thread_objs.get()->at(i))->execute(); });
thread_list[i] = thread; thread_list[i] = thread;
} }
for (auto thread : thread_list) { for (auto thread : thread_list) {
thread->join(); thread->join();
} }
while(true); while(true);
return 0; return 0;