fork download
  1. #include <iostream>
  2. #include <sys/mman.h>
  3. #include <sys/types.h>
  4. #include <sys/socket.h>
  5. #include <netinet/in.h>
  6. #include <netinet/tcp.h>
  7. #include <unistd.h>
  8. #include <sched.h>
  9. #include <exception>
  10. #include <string.h>
  11. #include <thread>
  12. #include <atomic>
  13. #include <arpa/inet.h>
  14. #include <sys/fcntl.h>
  15.  
  16. int safe_call(int ret, const char * ctx) {
  17. // fprintf(stderr, "%s == %d, errno(%d) == %s\n", ctx, ret, errno, strerror(errno));
  18. if(ret == -1) throw std::runtime_error(std::string(ctx) + " == " + std::to_string(ret) + ", errno(" + std::to_string(errno) + ')' + " == " + strerror(errno));
  19. return ret;
  20. }
  21. #define safe_call(call) safe_call(call, #call)
  22.  
  23.  
  24.  
  25. class alignas(64) worker {
  26. public:
  27.  
  28. void run(int listen_fd) {
  29. this->listen_fd = listen_fd;
  30. std::thread([this]() {
  31. work();
  32. }).detach();
  33. }
  34.  
  35. protected:
  36.  
  37. void work() {
  38. fprintf(stderr, "start thread(%lu)\n", id);
  39.  
  40. while(int accept_fd = safe_call(accept(listen_fd, nullptr, nullptr))) {
  41. fprintf(stderr, "accept thread(%lu)\n", id);
  42. uint64_t buff[(1024 * 10) / sizeof(uint64_t)];
  43. safe_call(read(accept_fd, buff, sizeof(uint64_t)));
  44. for(auto & x : buff) x = buff[0];
  45. auto it = std::begin(buff), end = std::end(buff);
  46. do {
  47. safe_call(write(accept_fd, it, 1024));
  48. } while((it += (1024 / sizeof(uint64_t))) < end);
  49. close(accept_fd);
  50. sleep(10);
  51. }
  52. }
  53.  
  54. protected:
  55. size_t id = get_tid();
  56. int listen_fd;
  57. protected:
  58. size_t get_tid() {
  59. return tid_count++;
  60. }
  61. static inline size_t tid_count = 0;;
  62. };
  63.  
  64.  
  65. int listen_to(in_addr_t addr, uint16_t port) {
  66. constexpr size_t n = 100;
  67. sockaddr_in saddr{};
  68. saddr.sin_family = AF_INET;
  69. saddr.sin_port = htons(port);
  70. saddr.sin_addr.s_addr = htonl(addr);
  71. int listen_fd = safe_call(socket(AF_INET, SOCK_STREAM, 0));
  72. int option = 1;
  73. safe_call(setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)));
  74. safe_call(bind(listen_fd, (__CONST_SOCKADDR_ARG)&saddr, sizeof(saddr)));
  75. safe_call(listen(listen_fd, n));
  76. return listen_fd;
  77. }
  78.  
  79. worker workers[10000];
  80.  
  81. int main() {
  82. int listen_fd = listen_to(INADDR_LOOPBACK, 8888);
  83.  
  84. for(auto & w : workers) w.run(listen_fd);
  85. while(1) {sleep(1);};
  86. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:61:36: error: ‘tid_count’ declared as an ‘inline’ field
   static inline size_t tid_count = 0;;
                                    ^
prog.cpp:61:36: error: ISO C++ forbids in-class initialization of non-const static member ‘worker::tid_count’
stdout
Standard output is empty