Example #1
0
/**
 * @brief Initialize a stream.
 * @protected
 *
 * @warning This function must only be used to implement a subclass of
 * @ref SquashStream.  Streams returned by other functions will
 * already be initialized, and you *must* *not* call this function on
 * them; doing so will likely trigger a memory leak.
 *
 * @param stream The stream to initialize.
 * @param codec The codec to use.
 * @param stream_type The stream type.
 * @param options The options.
 * @param destroy_notify Function to call to destroy the instance.
 *
 * @see squash_object_init
 */
void
squash_stream_init (void* stream,
                    SquashCodec* codec,
                    SquashStreamType stream_type,
                    SquashOptions* options,
                    SquashDestroyNotify destroy_notify) {
    SquashStream* s;

    assert (stream != NULL);

    s = (SquashStream*) stream;

    squash_object_init (stream, false, destroy_notify);

    s->next_in = NULL;
    s->avail_in = 0;
    s->total_in = 0;

    s->next_out = NULL;
    s->avail_out = 0;
    s->total_out = 0;

    s->codec = codec;
    s->options = (options != NULL) ? squash_object_ref (options) : NULL;
    s->stream_type = stream_type;
    s->state = SQUASH_STREAM_STATE_IDLE;

    s->user_data = NULL;
    s->destroy_user_data = NULL;

    if (codec->impl.create_stream == NULL && codec->impl.splice != NULL) {
        s->priv = squash_malloc (sizeof (SquashStreamPrivate));

        mtx_init (&(s->priv->io_mtx), mtx_plain);
        mtx_lock (&(s->priv->io_mtx));

        s->priv->request = SQUASH_OPERATION_INVALID;
        cnd_init (&(s->priv->request_cnd));

        s->priv->result = SQUASH_STATUS_INVALID;
        cnd_init (&(s->priv->result_cnd));

        s->priv->finished = false;
#if !defined(NDEBUG)
        int res =
#endif
            thrd_create (&(s->priv->thread), (thrd_start_t) squash_stream_thread_func, s);
        assert (res == thrd_success);

        while (s->priv->result == SQUASH_STATUS_INVALID)
            cnd_wait (&(s->priv->result_cnd), &(s->priv->io_mtx));
        s->priv->result = SQUASH_STATUS_INVALID;
    } else {
        s->priv = NULL;
    }
}
Example #2
0
void rd_kafka_timers_init (rd_kafka_timers_t *rkts, rd_kafka_t *rk) {
        memset(rkts, 0, sizeof(*rkts));
        rkts->rkts_rk = rk;
        TAILQ_INIT(&rkts->rkts_timers);
        mtx_init(&rkts->rkts_lock, mtx_plain);
        cnd_init(&rkts->rkts_cond);
}
Example #3
0
int main(void)
{
	SetConsoleTitle(TITLE);

	mtx_init(&gmutex, mtx_plain);
	cnd_init(&gcond);

	init_timer();
	init_path();
	init_strings();
	init_server();
	initpackets();
	//test_map(1);
	thrd_create(&t1, initsocket, (void*)0);
	thrd_create(&t2, commands, (void*)0);
	server_loop();
	destroy_server();
	mtx_destroy(&gmutex);
	cnd_destroy(&gcond);
#if _DEBUG
	VLDReportLeaks();
#endif

	exit(TRUE);// Exit program
}
Example #4
0
/*
====================
TFile_StartServer
====================
*/
void TFile_StartServer( void ) {
	server_message_t message;

	if ( !server_initialized ) {
		T_FatalError( "TFile_StartServer: Server is not initialized" );
	}

	if ( server_running ) {
		T_FatalError( "TFile_StartServer: Server is already running" );
	}

	cnd_init( &server_condition );
	mtx_init( &server_mutex, mtx_plain );
	mtx_lock( &server_mutex );

	message.ip_socket = server_socket;
	message.ip6_socket = server_socket6;
	if ( thrd_create( &server_thread, ServerThread, &message ) != thrd_success ) {
		T_FatalError( "TFile_StartServer: Unable to create thread" );
	}

	cnd_wait( &server_condition, &server_mutex );

	mtx_destroy( &server_mutex );
	cnd_destroy( &server_condition );

	server_running = t_true;
}
Example #5
0
File: db.c Project: jlsandell/Craft
void db_worker_start(char *path) {
    if (!db_enabled) {
        return;
    }
    ring_alloc(&ring, 1024);
    mtx_init(&mtx, mtx_plain);
    cnd_init(&cnd);
    thrd_create(&thrd, db_worker_run, path);
}
Example #6
0
SyncTileList* make_synclist() {
	SyncTileList* tl = (SyncTileList*)malloc(sizeof(SyncTileList));
	tl->count = 0;
	tl->first = 0;
	tl->last = 0;
	mtx_init(&tl->mtx,1);// 1 or 8??
	cnd_init(&tl->cnd);
	return tl;
}
Example #7
0
/**
 * Initialize a queue.
 */
void rd_kafka_q_init (rd_kafka_q_t *rkq, rd_kafka_t *rk) {
        rd_kafka_q_reset(rkq);
	rkq->rkq_fwdq   = NULL;
        rkq->rkq_refcnt = 1;
        rkq->rkq_flags  = RD_KAFKA_Q_F_READY;
        rkq->rkq_rk     = rk;
	mtx_init(&rkq->rkq_lock, mtx_plain);
	cnd_init(&rkq->rkq_cond);
}
Example #8
0
sfgeChannel sfgeRegisterChannel( const char *id ) {
    int c;
    mtx_lock(&messengerLock);
    c = channelCount;
    channels[c].id = id;
    channels[c].data = malloc(CHAN_BUF_SIZE);
    channels[c].readIndex = 0;
    channels[c].writeIndex = 0;
    cnd_init(&channels[c].readCond);
    cnd_init(&channels[c].writeCond);
    mtx_init(&channels[c].mutex, mtx_plain);
    channelCount++;
    mtx_unlock(&messengerLock);
    /* If any threads are waiting on a specific channel, signal them to check
     * again. */
    cnd_broadcast(&requireCond);
    return c;
}
Example #9
0
bool RWMutex::init()
{
	if(!initialized)
	{
		mtx_init(&mtxExclusiveAccess, mtx_plain | mtx_recursive);
		mtx_init(&mtxSharedAccessCompleted, mtx_plain | mtx_recursive);
		cnd_init(&cndSharedAccessCompleted);
		initialized = true;
	}
	return true;
}
COND_HANDLE Condition_Init(void)
{
    // Codes_SRS_CONDITION_18_002: [ Condition_Init shall create and return a CONDITION_HANDLE ]
    cnd_t* cond = (cnd_t*)malloc(sizeof(cnd_t));
    if (cond != NULL)
    {
        cnd_init(cond);
    }
    // Codes_SRS_CONDITION_18_008: [ Condition_Init shall return NULL if it fails to allocate the CONDITION_HANDLE ]
    return cond;
}
Example #11
0
int stack10_Constructor(Stack10 *s){
	int ret;
	
	ret = mtx_init(&s->mtx_, mtx_plain);
	if(ret != thrd_success){
		return ret;
	}
	
	ret = cnd_init(&s->cnd_push_);
	if(ret != thrd_success){
		return ret;
	}

	ret = cnd_init(&s->cnd_pop_);
	if(ret != thrd_success){
		return ret;
	}

	return 0;
}
Example #12
0
static void do_test_apis (rd_kafka_type_t cltype) {
        rd_kafka_t *rk;
        char errstr[512];
        rd_kafka_queue_t *mainq, *backgroundq;
        rd_kafka_conf_t *conf;

        mtx_init(&last_event_lock, mtx_plain);
        cnd_init(&last_event_cnd);

        do_test_unclean_destroy(cltype, 0/*tempq*/);
        do_test_unclean_destroy(cltype, 1/*mainq*/);

        test_conf_init(&conf, NULL, 0);
        /* Remove brokers, if any, since this is a local test and we
         * rely on the controller not being found. */
        test_conf_set(conf, "bootstrap.servers", "");
        test_conf_set(conf, "socket.timeout.ms", MY_SOCKET_TIMEOUT_MS_STR);
        /* For use with the background queue */
        rd_kafka_conf_set_background_event_cb(conf, background_event_cb);

        rk = rd_kafka_new(cltype, conf, errstr, sizeof(errstr));
        TEST_ASSERT(rk, "kafka_new(%d): %s", cltype, errstr);

        mainq = rd_kafka_queue_get_main(rk);
        backgroundq = rd_kafka_queue_get_background(rk);

        do_test_options(rk);

        do_test_CreateTopics("temp queue, no options", rk, NULL, 0, 0);
        do_test_CreateTopics("temp queue, no options, background_event_cb",
                             rk, backgroundq, 1, 0);
        do_test_CreateTopics("temp queue, options", rk, NULL, 0, 1);
        do_test_CreateTopics("main queue, options", rk, mainq, 0, 1);

        do_test_DeleteTopics("temp queue, no options", rk, NULL, 0);
        do_test_DeleteTopics("temp queue, options", rk, NULL, 1);
        do_test_DeleteTopics("main queue, options", rk, mainq, 1);

        do_test_mix(rk, mainq);

        do_test_configs(rk, mainq);

        rd_kafka_queue_destroy(backgroundq);
        rd_kafka_queue_destroy(mainq);

        rd_kafka_destroy(rk);

        mtx_destroy(&last_event_lock);
        cnd_destroy(&last_event_cnd);

}
Example #13
0
int main(int argc, char** argv)
{
  int res;

  mtx_init(&gMutex, mtx_plain);
  cnd_init(&gCond);

  res = tests_run(unit_tests, argc, argv);

  mtx_destroy(&gMutex);
  cnd_destroy(&gCond);

  return res;
}
Example #14
0
struct util_ringbuffer *util_ringbuffer_create( unsigned dwords )
{
   struct util_ringbuffer *ring = CALLOC_STRUCT(util_ringbuffer);
   if (!ring)
      return NULL;

   assert(util_is_power_of_two_or_zero(dwords));
   
   ring->buf = MALLOC( dwords * sizeof(unsigned) );
   if (ring->buf == NULL)
      goto fail;

   ring->mask = dwords - 1;

   cnd_init(&ring->change);
   (void) mtx_init(&ring->mutex, mtx_plain);
   return ring;

fail:
   FREE(ring->buf);
   FREE(ring);
   return NULL;
}
Example #15
0
/* This is the main program (i.e. the main thread) */
int main(void)
{
  /* Initialization... */
  mtx_init(&gMutex, mtx_plain);
  cnd_init(&gCond);

  /* Test 1: thread arguments & return values */
  printf("PART I: Thread arguments & return values\n");
  {
    thrd_t t1, t2, t3, t4;
    int id1, id2, id3, id4, ret1, ret2, ret3, ret4;

    /* Start a bunch of child threads */
    id1 = 1;
    thrd_create(&t1, ThreadIDs, (void*)&id1);
    thrd_join(t1, &ret1);
    printf(" Thread 1 returned %d.\n", ret1);
    id2 = 2;
    thrd_create(&t2, ThreadIDs, (void*)&id2);
    thrd_join(t2, &ret2);
    printf(" Thread 2 returned %d.\n", ret2);
    id3 = 3;
    thrd_create(&t3, ThreadIDs, (void*)&id3);
    thrd_join(t3, &ret3);
    printf(" Thread 3 returned %d.\n", ret3);
    id4 = 4;
    thrd_create(&t4, ThreadIDs, (void*)&id4);
    thrd_join(t4, &ret4);
    printf(" Thread 4 returned %d.\n", ret4);
  }

  /* Test 2: compile time thread local storage */
  printf("PART II: Compile time thread local storage\n");
#ifndef NO_CT_TLS
  {
    thrd_t t1;

    /* Clear the TLS variable (it should keep this value after all threads are
       finished). */
    gLocalVar = 1;
    printf(" Main gLocalVar is %d.\n", gLocalVar);

    /* Start a child thread that modifies gLocalVar */
    thrd_create(&t1, ThreadTLS, NULL);
    thrd_join(t1, NULL);

    /* Check if the TLS variable has changed */
    if(gLocalVar == 1)
      printf(" Main gLocalID was not changed by the child thread - OK!\n");
    else
      printf(" Main gLocalID was changed by the child thread - FAIL!\n");
  }
#else
  printf(" Compile time TLS is not supported on this platform...\n");
#endif

  /* Test 3: mutex locking */
  printf("PART III: Mutex locking (100 threads x 10000 iterations)\n");
  {
    thrd_t t[100];
    int i;

    /* Clear the global counter. */
    gCount = 0;

    /* Start a bunch of child threads */
    for (i = 0; i < 100; ++ i)
    {
      thrd_create(&t[i], ThreadLock, NULL);
    }

    /* Wait for the threads to finish */
    for (i = 0; i < 100; ++ i)
    {
      thrd_join(t[i], NULL);
    }

    /* Check the global count */
    printf(" gCount = %d\n", gCount);
  }

  /* Test 4: condition variable */
  printf("PART IV: Condition variable (40 + 1 threads)\n");
  {
    thrd_t t1, t[40];
    int i;

    /* Set the global counter to the number of threads to run. */
    gCount = 40;

    /* Start the waiting thread (it will wait for gCount to reach zero). */
    thrd_create(&t1, ThreadCondition2, NULL);

    /* Start a bunch of child threads (these will decrease gCount by 1 when they
       finish) */
    for (i = 0; i < 40; ++ i)
    {
      thrd_create(&t[i], ThreadCondition1, NULL);
    }

    /* Wait for the waiting thread to finish */
    thrd_join(t1, NULL);

    /* Wait for the other threads to finish */
    for (i = 0; i < 40; ++ i)
    {
      thrd_join(t[i], NULL);
    }
  }

  /* Test 5: yield */
  printf("PART V: Yield (40 + 1 threads)\n");
  {
    thrd_t t[40];
    int i;

    /* Start a bunch of child threads */
    for (i = 0; i < 40; ++ i)
    {
      thrd_create(&t[i], ThreadYield, NULL);
    }

    /* Yield... */
    thrd_yield();

    /* Wait for the threads to finish */
    for (i = 0; i < 40; ++ i)
    {
      thrd_join(t[i], NULL);
    }
  }

  /* Test 6: Sleep */
  printf("PART VI: Sleep (10 x 100 ms)\n");
  {
    int i;
    struct timespec ts;

    printf(" Sleeping");
    fflush(stdout);
    for (i = 0; i < 10; ++ i)
    {
      /* Calculate current time + 100ms */
      clock_gettime(TIME_UTC, &ts);
      ts.tv_nsec += 100000000;
      if (ts.tv_nsec >= 1000000000)
      {
        ts.tv_sec++;
        ts.tv_nsec -= 1000000000;
      }

      /* Sleep... */
      thrd_sleep(&ts, NULL);

      printf(".");
      fflush(stdout);
    }
    printf("\n");
  }

  /* Test 7: Time */
  printf("PART VII: Current time (UTC), three times\n");
  {
    struct timespec ts;
    clock_gettime(TIME_UTC, &ts);
    printf(" Time = %ld.%09ld\n", (long)ts.tv_sec, ts.tv_nsec);
    clock_gettime(TIME_UTC, &ts);
    printf(" Time = %ld.%09ld\n", (long)ts.tv_sec, ts.tv_nsec);
    clock_gettime(TIME_UTC, &ts);
    printf(" Time = %ld.%09ld\n", (long)ts.tv_sec, ts.tv_nsec);
  }

  /* FIXME: Implement some more tests for the TinyCThread API... */

  /* Finalization... */
  mtx_destroy(&gMutex);
  cnd_destroy(&gCond);

  return 0;
}
Example #16
0
int NetProbeServerTP(char *TCPPort, char *threadnum){

	//Create a thread pool
	cnd_init(&cond);
	mtx_init(&ThMutex, mtx_plain);
	int ThreadNum = atoi(threadnum);
	
	for (int j = 0; j < ThreadNum; j++){
		thrd_t TCPSThread;
		if (thrd_create(&TCPSThread, TPTCPChild, NULL) == thrd_error){
			printf("Create thread is failed\n");
			return 0;
		}
		else{
			printf("Creating thread %d in threadpool mode.\n", j+1);
			if (j == ThreadNum-1){
				printf("Create threadpool with %d threads in totoal.\n", j+1);
				printf("Waiting for client to connect...\n");
			}
		}
	}
	
	SOCKET Socket, new_socket;
	struct sockaddr_in server, client;
	int  recv_len;
	socklen_t c;
	c = sizeof(struct sockaddr_in);
	char *ReceiveBuf;
	ReceiveBuf = (char *)malloc(sizeof(char)* 1024);

	//Initialize Winsock
#ifdef WIN32
	WSADATA wsa;
	if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0){
		printf("Failed to Initialize, Error code : %d", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
#endif
	if ((Socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET){
		printf("Could not create socket : d%", WSAGetLastError());
	}
	memset(&server, 0, sizeof(struct sockaddr_in));
	memset(&client, 0, sizeof(struct sockaddr_in));
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(atoi(TCPPort));
	if (bind(Socket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR){
		printf("Bind failed with error code : %d", WSAGetLastError());
		exit(EXIT_FAILURE);
	}
	listen(Socket, 100);
	
	//Listening to new TCP connection
	while (1){
		memset(ReceiveBuf, 0, 1024);
		if ((new_socket = accept(Socket, (struct sockaddr *)&client, &c)) == INVALID_SOCKET){
			printf("accept failed with error code: %d\n", WSAGetLastError());
			return 0;
		}
		else{
			mtx_lock(&ThMutex);
			SocketQueue.Enqueue(&SocketQueue, new_socket);
			mtx_unlock(&ThMutex);
			cnd_signal(&cond);
		}
		Sleep(2);
	}
	closesocket(Socket);
#ifdef WIN32
	WSACleanup();
#endif
	return 0;
}
Example #17
0
int main(int argc, char** argv)
{
    int ch, width, height;
    thrd_t physics_thread = 0;
    GLFWwindow* window;
    GLFWmonitor* monitor = NULL;

    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'f':
                monitor = glfwGetPrimaryMonitor();
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
        }
    }

    if (monitor)
    {
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width  = mode->width;
        height = mode->height;
    }
    else
    {
        width  = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to create GLFW window\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    if (monitor)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(1);

    glfwSetWindowSizeCallback(window, resize_callback);
    glfwSetKeyCallback(window, key_callback);

    // Set initial aspect ratio
    glfwGetWindowSize(window, &width, &height);
    resize_callback(window, width, height);

    // Upload particle texture
    glGenTextures(1, &particle_tex_id);
    glBindTexture(GL_TEXTURE_2D, particle_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture);

    // Upload floor texture
    glGenTextures(1, &floor_tex_id);
    glBindTexture(GL_TEXTURE_2D, floor_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture);

    if (glfwExtensionSupported("GL_EXT_separate_specular_color"))
    {
        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT,
                      GL_SEPARATE_SPECULAR_COLOR_EXT);
    }

    // Set filled polygon mode as default (not wireframe)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    wireframe = 0;

    // Set initial times
    thread_sync.t  = 0.0;
    thread_sync.dt = 0.001f;
    thread_sync.p_frame = 0;
    thread_sync.d_frame = 0;

    mtx_init(&thread_sync.particles_lock, mtx_timed);
    cnd_init(&thread_sync.p_done);
    cnd_init(&thread_sync.d_done);

    if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetTime(0.0);

    while (!glfwWindowShouldClose(window))
    {
        draw_scene(window, glfwGetTime());

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    thrd_join(physics_thread, NULL);

    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Example #18
0
int main(int argc, char** argv)
{
    signal(SIGINT, IntHandler);

    Server serv;

    // Initialize the server
    InitConfig(&serv.conf, argv[1], argc, argv);
    
    if(!serv.conf.name) {
        fprintf(stderr, "Script doesn't specify a server name.\n");
        return 1;
    }

    if(!serv.conf.port) {
        fprintf(stderr, "Script doesn't specify a port.\n");
        return 1;
    }

	printf("Successfully configured server.\n"
		"Name: %s\n"
		"Port: %s\n"
		"Num Threads: %d\n"
		"Cycles Per Loop: %d\n"
		"Num Routes: %d\n", serv.conf.name, serv.conf.port, serv.conf.numThreads, serv.conf.cyclesPerLoop, sb_count(serv.conf.routes));

    InitList(&serv.clientQueue, sizeof(Sock));
    InitList(&serv.requestQueue, sizeof(ClientRequest));

    cnd_init(&serv.updateLoop);
    cnd_init(&serv.newConn);

    // The loop thread is responsible for initializing LoopData

    thrd_t loopThread, connThread;

    thrd_create(&loopThread, MainLoop, &serv);
    thrd_create(&connThread, ConnLoop, &serv);

    // Initialize winsock and listen for clients
    WSADATA wsaData;
    SOCKET listenSocket;

    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if(iResult != 0) {
        fprintf(stderr, "WSAStartup failed: %d\n", iResult);
        return 1;
    }

    struct addrinfo hints;
    
    ZeroMemory(&hints, sizeof(hints));

    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = IPPROTO_TCP;
    hints.ai_flags = AI_PASSIVE;

    struct addrinfo* result;

    iResult = getaddrinfo(NULL, serv.conf.port, &hints, &result);
    if(iResult != 0) {
        fprintf(stderr, "getaddrinfo failed: %d\n", iResult);
        WSACleanup();
        return 1;
    }
    
    listenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);

    if(listenSocket == INVALID_SOCKET) {
        fprintf(stderr, "Error at socket(): %d\n", WSAGetLastError());
        freeaddrinfo(result); 
        WSACleanup();
        return 1;
    }

    freeaddrinfo(result);

    iResult = bind(listenSocket, result->ai_addr, (int)result->ai_addrlen);

    if(iResult == SOCKET_ERROR) {
        fprintf(stderr, "bind failed with error: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }

    if(listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        fprintf(stderr, "listen failed with error: %d\n", WSAGetLastError());
        closesocket(listenSocket);
        WSACleanup();
        return 1;
    }
	
	while (KeepRunning) {
		SOCKET clientSocket = accept(listenSocket, NULL, NULL);

		if (clientSocket == INVALID_SOCKET) {
			fprintf(stderr, "accept failed: %d\n", WSAGetLastError());
            continue;
		}

		int iMode = 1;
        if (ioctlsocket(clientSocket, FIONBIO, &iMode) == SOCKET_ERROR) {
            fprintf(stderr, "ioctlsocket failed: %d\n", WSAGetLastError());
            continue;
        }

        Sock sock;

        InitSock(&sock, (void*)clientSocket);
        
        ListPushBack(&serv.clientQueue, &sock);

        cnd_signal(&serv.newConn);
	}

    WSACleanup();

    thrd_join(&connThread, NULL);
	thrd_join(&loopThread, NULL);

    cnd_destroy(&serv.newConn);
    cnd_destroy(&serv.updateLoop);

	DestroyList(&serv.requestQueue);
	DestroyList(&serv.clientQueue);

    DestroyConfig(&serv.conf);

	return 0;
}
Example #19
0
/**
 * @brief Test that Metadata requests are retried properly when
 *        timing out due to high broker rtt.
 */
static void do_test_low_socket_timeout (const char *topic) {
        rd_kafka_t *rk;
        rd_kafka_conf_t *conf;
        rd_kafka_topic_t *rkt;
        rd_kafka_resp_err_t err;
        const struct rd_kafka_metadata *md;
        int res;

        mtx_init(&ctrl.lock, mtx_plain);
        cnd_init(&ctrl.cnd);

        TEST_SAY("Test Metadata request retries on timeout\n");

        test_conf_init(&conf, NULL, 60);
        test_conf_set(conf, "socket.timeout.ms", "1000");
        test_conf_set(conf, "socket.max.fails", "12345");
        test_conf_set(conf, "retry.backoff.ms", "5000");
        /* Avoid api version requests (with their own timeout) to get in
         * the way of our test */
        test_conf_set(conf, "api.version.request", "false");
        test_socket_enable(conf);
        test_curr->connect_cb = connect_cb;
        test_curr->is_fatal_cb = is_fatal_cb;

        rk = test_create_handle(RD_KAFKA_PRODUCER, conf);
        rkt = test_create_producer_topic(rk, topic, NULL);

        TEST_SAY("Waiting for sockem connect..\n");
        mtx_lock(&ctrl.lock);
        while (!ctrl.skm)
                cnd_wait(&ctrl.cnd, &ctrl.lock);
        mtx_unlock(&ctrl.lock);

        TEST_SAY("Connected, fire off a undelayed metadata() to "
                 "make sure connection is up\n");

        err = rd_kafka_metadata(rk, 0, rkt, &md, tmout_multip(2000));
        TEST_ASSERT(!err, "metadata(undelayed) failed: %s",
                    rd_kafka_err2str(err));
        rd_kafka_metadata_destroy(md);

        if (thrd_create(&ctrl.thrd, ctrl_thrd_main, NULL) != thrd_success)
                TEST_FAIL("Failed to create sockem ctrl thread");

        set_delay(0, 3000); /* Takes effect immediately */

        /* After two retries, remove the delay, the third retry
         * should kick in and work. */
        set_delay(((1000 /*socket.timeout.ms*/ +
                    5000 /*retry.backoff.ms*/) * 2) - 2000, 0);

        TEST_SAY("Calling metadata() again which should succeed after "
                 "3 internal retries\n");
        /* Metadata should be returned after the third retry */
        err = rd_kafka_metadata(rk, 0, rkt, &md,
                                ((1000 /*socket.timeout.ms*/ +
                                  5000 /*retry.backoff.ms*/) * 2) + 5000);
        TEST_SAY("metadata() returned %s\n", rd_kafka_err2str(err));
        TEST_ASSERT(!err, "metadata(undelayed) failed: %s",
                    rd_kafka_err2str(err));
        rd_kafka_metadata_destroy(md);

        rd_kafka_topic_destroy(rkt);
        rd_kafka_destroy(rk);

        /* Join controller thread */
        mtx_lock(&ctrl.lock);
        ctrl.term = 1;
        mtx_unlock(&ctrl.lock);
        thrd_join(ctrl.thrd, &res);

        cnd_destroy(&ctrl.cnd);
        mtx_destroy(&ctrl.lock);
}
Example #20
0
int sfgeMessengerStart() {
    mtx_init(&messengerLock, mtx_plain);
    cnd_init(&requireCond);
    channelCount = 0;
    return 1;
}