Skip to content

Commit 4fd895c

Browse files
committed
Add HelloWorldThreaded and (actually) fix race
1 parent 940980f commit 4fd895c

3 files changed

Lines changed: 40 additions & 2 deletions

File tree

Makefile

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ examples:
66
clang++ -flto -O3 -s *.o -o HelloWorld
77
rm *.o
88

9+
# HelloWorldThreaded (non-SSL, non-Zlib compile)
10+
clang -DLIBUS_NO_SSL -flto -O3 -c -IuSockets/src uSockets/src/*.c uSockets/src/eventing/*.c
11+
clang++ -DLIBUS_NO_SSL -DUWS_NO_ZLIB -flto -O3 -c -std=c++17 -Isrc -IuSockets/src examples/HelloWorldThreaded.cpp
12+
clang++ -lpthread -flto -O3 -s *.o -o HelloWorldThreaded
13+
rm *.o
14+
915
# EchoServer (non-SSL, non-Zlib compile)
1016
clang -DLIBUS_NO_SSL -flto -O3 -c -IuSockets/src uSockets/src/*.c uSockets/src/eventing/*.c
1117
clang++ -DLIBUS_NO_SSL -DUWS_NO_ZLIB -flto -O3 -c -std=c++17 -Isrc -IuSockets/src examples/EchoServer.cpp

examples/HelloWorldThreaded.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include "App.h"
2+
#include <thread>
3+
#include <algorithm>
4+
5+
int main() {
6+
/* Overly simple hello world app, using multiple threads */
7+
std::vector<std::thread *> threads(std::thread::hardware_concurrency());
8+
9+
std::transform(threads.begin(), threads.end(), threads.begin(), [](std::thread *t) {
10+
return new std::thread([]() {
11+
12+
uWS::App().get("/*", [](auto *res, auto *req) {
13+
res->end("Hello world!");
14+
}).listen(3000, [](auto *token) {
15+
if (token) {
16+
std::cout << "Thread " << std::this_thread::get_id() << " listening on port " << 3000 << std::endl;
17+
} else {
18+
std::cout << "Thread " << std::this_thread::get_id() << " failed to listen on port 3000" << std::endl;
19+
}
20+
}).run();
21+
22+
});
23+
});
24+
25+
std::for_each(threads.begin(), threads.end(), [](std::thread *t) {
26+
t->join();
27+
});
28+
}

src/Loop.h

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
#include <libusockets_new.h>
2525

2626
#include <iostream>
27-
#include <atomic>
27+
#include <thread>
2828

2929
namespace uWS {
3030
struct Loop {
@@ -86,9 +86,13 @@ struct Loop {
8686
public:
8787
/* Returns the default loop if called from one thread, or a dedicated per-thread loop if called from multiple threads */
8888
static Loop *defaultLoop() {
89+
/* Lock this whole function */
90+
static std::mutex m;
91+
std::lock_guard<std::mutex> lock(m);
92+
8993
/* Deliver and attach the default loop to the first thread who calls us */
9094
static thread_local bool ownsDefaultLoop;
91-
static std::atomic<Loop *> defaultLoop;
95+
static Loop *defaultLoop;
9296
if (!defaultLoop) {
9397
ownsDefaultLoop = true;
9498
defaultLoop = create(true);

0 commit comments

Comments
 (0)