コード例 #1
0
ファイル: ntp_prio_q.c プロジェクト: qicny/freebsd
void
test_AppendQueues(void) {
    queue* q1 = create_queue();
    queue* q2 = create_queue();
    queue* q3 = create_queue();
    queue* q4 = create_queue();
    queue* q5 = create_queue();

    // append empty queue to empty queue
    append_queue(q1, q2);	// destroys q2

    element *e1_ptr, *e2_ptr, *e3_ptr, *e4_ptr, *e5_ptr, *e6_ptr;
    e1_ptr = (element*)debug_get_node(sizeof(element));
    e2_ptr = (element*)debug_get_node(sizeof(element));
    e3_ptr = (element*)debug_get_node(sizeof(element));
    e4_ptr = (element*)debug_get_node(sizeof(element));
    e5_ptr = (element*)debug_get_node(sizeof(element));
    e6_ptr = (element*)debug_get_node(sizeof(element));

    enqueue(q1, e1_ptr);
    enqueue(q1, e2_ptr);
    enqueue(q1, e3_ptr);


    // append empty queue to non empty queue
    append_queue(q1, q3);	// destroys q3
    TEST_ASSERT_EQUAL(3, get_no_of_elements(q1));

    // append non empty queue to empty queue
    append_queue(q4, q1);	// destroys q1
    TEST_ASSERT_EQUAL(3, get_no_of_elements(q4));

    enqueue(q5, e4_ptr);
    enqueue(q5, e5_ptr);

    // append non empty queue to non empty queue
    append_queue(q4, q5);	// destroys q5
    TEST_ASSERT_EQUAL(5, get_no_of_elements(q4));

    dequeue(q4);
    dequeue(q4);
    dequeue(q4);
    dequeue(q4);
    dequeue(q4);

    free_node(e1_ptr);
    free_node(e2_ptr);
    free_node(e3_ptr);
    free_node(e4_ptr);
    free_node(e5_ptr);
    free_node(e6_ptr);

    TEST_ASSERT_EQUAL(0, get_no_of_elements(q4));

    // destroy_queue(q1);	// destroyed already
    // destroy_queue(q2);	// destroyed already
    // destroy_queue(q3);	// destroyed already
    destroy_queue(q4);
    // destroy_queue(q5);	// destroyed already
}
コード例 #2
0
ファイル: http_client.c プロジェクト: deadcafe/trash
bool
init_http_client() {
  debug( "Initializaing HTTP client." );

  assert( http_client_thread == NULL );
  assert( http_client_efd == -1 );
  assert( main_efd == -1 );
  assert( transactions == NULL );

  http_client_efd = create_event_fd();
  assert( http_client_efd >= 0 );
  http_client_notify_count = 0;
  set_fd_handler( http_client_efd, NULL, NULL, notify_http_client_actually, &http_client_notify_count );
  set_writable( http_client_efd, false );

  main_efd = create_event_fd();
  assert( main_efd >= 0 );
  set_fd_handler( main_efd, retrieve_http_transactions_from_http_client, NULL, NULL, NULL );
  set_readable( main_efd, true );

  assert( main_to_http_client_queue == NULL );
  assert( http_client_to_main_queue == NULL );

  main_to_http_client_queue = create_queue();
  assert( main_to_http_client_queue != NULL );
  http_client_to_main_queue = create_queue();
  assert( http_client_to_main_queue != NULL );

  create_http_transaction_db();

  debug( "Initialization completed." );

  return true;
}
コード例 #3
0
ファイル: main.c プロジェクト: evolutek/motorboard_emulator
int main(int argc, char** argv){

  static pthread_t thread_serial_id;
  static pthread_t thread_flush_serial;
  static pthread_t thread_commands;

  Queue queue_input;
  Queue queue_output;

  create_queue(&queue_input);
  create_queue(&queue_output);

  int fd_;
  connect_pty (&fd_);

  data_t data = {
    .fd = &fd_, 
    .input = queue_input,
    .output = queue_output,
    .mutex = PTHREAD_MUTEX_INITIALIZER,
  };

  int ret = pthread_create(&thread_serial_id, NULL, serial_simulation,
      &data);
  int ret2 = pthread_create(&thread_flush_serial, NULL, flush_serial,
      &data);
  int ret3 = pthread_create(&thread_commands, NULL, manage_commands,
      &data);

  pthread_join (thread_commands, NULL);
  pthread_join (thread_serial_id, NULL);
  pthread_join (thread_flush_serial, NULL);

  return EXIT_SUCCESS;
}
コード例 #4
0
//OpenMP: Given a search string, the function performs a multi-threaded search of the file system starting from the specified path name.
void search_for_string_openmp(char **argv)
{
	//What's going on, eh?
	printf("OPENMP Execution Started.\n");
	
	//  	1			2			3
	//<search string> <path> <# of threads>"
	//Collect the command line args
	char * to_find = argv[1];
	char * start_path = argv[2];
	unsigned int num_threads = atoi(argv[3]);
	unsigned int num_found = 0;
	
	//If there was some way to know where files were located on disk
	//To further optimize disk access patterns... that would be neat.
	
	//Ok two queues, one for directories to be searched through
	//The other is for filenames themselves
	queue_t * dir_queue = create_queue();
	queue_t * file_queue = create_queue();
	
	//We don't want queues being locked
	//unlocked very often so each thread will pull off a certain number
	//of items at a time to look at
	unsigned int num_files_per_queue_access = 10;
	unsigned int num_dirs_per_queue_access = 1;
	
	//Need to build up a buffer of files in the list before starting
	unsigned int file_queue_min_size = 1000;
	
	//So threads will first look to the dir queue to keep finding files
	//If no dirs exist then they will look in the file queue for files
	//to search through
	//Prime the dir queue with the starting directory
	place_in_queue(dir_queue, start_path);	  	
	
	//Start the timer
	struct timeval start;	
	gettimeofday(&start, NULL);
	
	//Let's get parallel up in here
	#pragma omp parallel num_threads(num_threads) shared(dir_queue, file_queue, num_found) private(num_threads)//num_files_per_queue_access, num_dirs_per_queue_access
	{
		//Do the search, yo.
		omp_grepr(to_find, num_threads, &num_found, dir_queue, file_queue,num_files_per_queue_access,num_dirs_per_queue_access,file_queue_min_size);
	}
	
	//Stop timer here and determine the elapsed time
	struct timeval stop;	
	gettimeofday(&stop, NULL);
	printf("OPENMP Overall execution time = %fs. \n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000));
	printf("OPENMP The string %s was found %d times within the file system. \n\n", to_find , num_found);
}
コード例 #5
0
int main()
{
	int pData;         //用来保存出队的元素值

	//创建队列并进行入队测试
	PQUEUE pS1 = create_queue();
	PQUEUE pS2 = create_queue();
	push(pS1,pS2,4);
	push(pS1,pS2,5);
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	if(pop(pS1,pS2,&pData))
		printf("%d is pop out\n",pData);
	else
		printf("Stack is empty,can not pop\n");
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	push(pS1,pS2,6);
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	push(pS1,pS2,7);
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	if(pop(pS1,pS2,&pData))
		printf("%d is pop out\n",pData);
	else
		printf("Stack is empty,can not pop\n");
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));	
	if(pop(pS1,pS2,&pData))
		printf("%d is pop out\n",pData);
	else
		printf("Stack is empty,can not pop\n");
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	if(pop(pS1,pS2,&pData))
		printf("%d is pop out\n",pData);
	else
		printf("Stack is empty,can not pop\n");
	printf("the length of pS1: %d\n",length(pS1));
	printf("the length of pS2: %d\n",length(pS2));
	if(pop(pS1,pS2,&pData))
		printf("%d is pop out\n",pData);
	else
		printf("Stack is empty,can not pop\n");

	return 0;
}
コード例 #6
0
ファイル: console.c プロジェクト: renax1991/krypton-os-remake
void* console_device(void * arg) {

    uint32_t scancode;
    iorq_t iorq;
    int i;
    char c;
    char * aux;
    
    memset(&keybd_device, 0, sizeof(device_t));
    strcpy(keybd_device.ln_link.name, "org.era.dev.console");
    keybd_device.iorq_queue = create_queue(10, sizeof(iorq_t));

    keybd_queue = create_queue(1, sizeof(uint32_t));
    register_interrupt_handler(IRQ1, &keypress_isr);
    monitor_writexy(0,24, " 1", 7, 0);
    
    for(;;) {
        queue_recv(keybd_device.iorq_queue, &iorq, QM_BLOCKING);
        if(iorq.io_desc == DC_READ) {
            i = 0;
            aux = (char *) iorq.io_dptr;
            memset(aux, 0, iorq.io_sz);
            
            while(1) {
                queue_recv(keybd_queue, &scancode, QM_BLOCKING);
                c = kbdus[scancode];
                if (c == '\n')
                    break;
                if ((c == '\b') && (i > 0)) {
                    aux[i] = '\0';
                    i--;
                    monitor_put('\b');
                    continue;
                }
                if (c == 0 || c == '\t' || i == (iorq.io_sz - 1))
                    continue;
                if(isprintable(c) ) {
                    aux[i++] = c;
                    monitor_put(c);
                }
            }
            monitor_put('\n');
            aux[i] = '\0';

            queue_send(iorq.io_response, NULL, QM_NONBLOCKING);
        }
    }
}
コード例 #7
0
ファイル: test_queue.c プロジェクト: braveyly/codefactory
/*
 * Function: int main(int argc, char args[])
 * Description: process main function
 * Input:  argc: parameter number
 *         args: parameter value array
 * Output: none
 * Return: function exit status
 * Others: none
 */
int main( )
{
	Queue	* q;
	Ele		* ele;

	q = create_queue( show_ele, delete_ele );

	ele = create_ele( 28, "liwei", 10, "hust++life" );
	in_queue( q, ele );

	ele = create_ele( 24, "lijia", 10, "hust++acon" );
	in_queue( q, ele );

	ele = create_ele( 26, "lijing", 10, "hust++acon" );
	in_queue( q, ele );

	queue_show( q );

	printf( "=============\n" );

	ele = out_queue( q );
	show_ele( ele );

	ele = out_queue( q );
	show_ele( ele );

	ele = out_queue( q );
	show_ele( ele );

	ele = out_queue( q );
	show_ele( ele );
}
コード例 #8
0
ファイル: problem_6.c プロジェクト: binhqnguyen/cs5460
int main(){
	queue_t *queue;
	int i = 0;
	int v = 0;
	queue = create_queue();
	if (queue == NULL){
		fprintf(stderr,"Error creating queue\n");
		return -EXIT_FAILURE;
	}
	assert (deq(&v,queue)==0);	/*deque an empty queue, print "Queue is empty"*/

	for (i = 0; i < 32; ++i)
		assert (enq(5,queue)==1);	/*fill the queue with 5*/

	for (i = 0; i < 32; ++i)
		assert (queue->value[i]==5);	/*check the entire queue*/

	assert (enq(5, queue)==0);	/*enque a full queue, print "Queue is full"*/

	assert (deq(&v, queue)==1);	/*deque the first element*/

	assert (enq(6, queue)==1);	/*enque 6*/

	for (i = 0; i < 32; i++)
		assert(deq(&v,queue)==1);
	assert (v==6);	/*the last element should be 6*/
	
	return EXIT_SUCCESS;
}
コード例 #9
0
ファイル: queue.c プロジェクト: melanc/algorithms
int main()
{
    int data_de = 0;         //用来保存出队的元素值

    //创建队列并进行入队测试
    PQUEUE pS = create_queue();
    en_queue(pS,2);
    en_queue(pS,4);
    en_queue(pS,6);
    traverse_queue(pS);

    //出队测试
    if(de_queue(pS,&data_de))
        printf("delete succeed,the deleted data is: %d\n",data_de);
    else
        printf("queue is empty! delete falied!\n");
    traverse_queue(pS);

    //销毁队列测试
    destroy_queue(pS);
    printf("queue destroyed!\n");
    traverse_queue(pS);

    return 0;
}
コード例 #10
0
TEST(PRIORITY_QUEUE,FULL){
	
	//try to get the full status of a non existent queue
	RESULT result = is_full(424234);
	EXPECT_EQ(result.code,TICKET_INVALID);
	
	//fill up the queue
	WELCOME_PACKET packet = create_queue();
	
	//if(packet.result.code == SUCCESS){
		
	for(int i = 0; i < MAXIMUM_NUMBER_OF_ELEMENTS_IN_A_QUEUE-1; i++){
		ELEMENT e = {i,i%10};
		EXPECT_EQ(enqueue(e,packet.ticket).code,SUCCESS);
		EXPECT_EQ(is_full(packet.ticket).code,QUEUE_IS_NOT_FULL);
	}
	
	ELEMENT e = {3,3};		
	enqueue(e,packet.ticket);
	
	EXPECT_EQ(is_full(packet.ticket).code,QUEUE_IS_FULL);
	
	enqueue(e,packet.ticket);
	EXPECT_EQ(is_full(packet.ticket).code,QUEUE_IS_FULL);
	

	enqueue(e,packet.ticket);
	EXPECT_EQ(is_full(packet.ticket).code,QUEUE_IS_FULL);
	
	//delete the queue then try to get the full status
	delete_queue(packet.ticket);
	EXPECT_EQ(is_full(packet.ticket).code,TICKET_INVALID);
	
}
コード例 #11
0
ファイル: toxav.c プロジェクト: iShift/ProjectTox-Core
/**
 * @brief Start new A/V session. There can only be one session at the time. If you register more
 *        it will result in undefined behaviour.
 *
 * @param messenger The messenger handle.
 * @param userdata The agent handling A/V session (i.e. phone).
 * @param video_width Width of video frame.
 * @param video_height Height of video frame.
 * @return ToxAv*
 * @retval NULL On error.
 */
ToxAv *toxav_new( Tox* messenger, ToxAvCodecSettings* codec_settings)
{
    ToxAv *av = calloc ( sizeof(ToxAv), 1);

    if (av == NULL)
        return NULL;

    av->messenger = (Messenger *)messenger;

    av->msi_session = msi_init_session(av->messenger);
    av->msi_session->agent_handler = av;

    av->rtp_sessions[0] = av->rtp_sessions [1] = NULL;

    /* NOTE: This should be user defined or? */
    av->j_buf = create_queue(codec_settings->jbuf_capacity);

    av->cs = codec_init_session(codec_settings->audio_bitrate, 
                                codec_settings->audio_frame_duration, 
                                codec_settings->audio_sample_rate,
                                codec_settings->audio_channels,
                                codec_settings->video_width,
                                codec_settings->video_height,
                                codec_settings->video_bitrate);

    return av;
}
コード例 #12
0
ファイル: Sequential_BFS.c プロジェクト: rosiakh/PGwZO
/// returns array of distances from source
int* sequential_BFS(int *C, int *R, int v, int src)
{
	Queue *q = create_queue(v);
	int *dist = (int*)malloc(sizeof(int)*v);

	for (int i = 0; i < v; ++i)
	{
		dist[i] = -1;
	}
	dist[src] = 0;

	enqueue(q, src);

	int a, b;
	while (!empty(q))
	{
		a = dequeue(q);

		for (int j = R[a]; j < R[a + 1]; ++j)
		{
			b = C[j];
			if (dist[b] == -1)
			{
				dist[b] = dist[a] + 1;
				enqueue(q, b);
			}
		}
	}

	return dist;
}
コード例 #13
0
void PriorityQueuetoString(fifo_queue *theArray) {
    //fifo_queue *theArray = thePQ->startOfArray;
    int i;
    for (i = 0; i < NumberOfPriorities; i++ ) {
        printf("Q%d:", i);
        //FIFOQueuetoString((theArray + i));
         fifo_queue *tempqueue = create_queue();
         fifo_queue *queue = &theArray[i];
    //printf("is_empty %d", is_empty(queue));
    //printf("not is_empty %d", !is_empty(queue));
    while (!is_empty(queue)) {
        
        //printf("size before dequeue %d", get_size(queue));
        PCB_p temp = dequeue(queue);
        //toStringShort(temp);
        printf("P%d", temp->pid);
        enqueue(tempqueue, temp);
        if (!is_empty(queue)){
            printf("->");
        } else {
            printf("-");    
        }
    }
    printf("*");
    //put the data back in the original queue
    while (!is_empty(tempqueue)) {
        enqueue(queue, dequeue(tempqueue));
    }
        printf("\n");
    }
}
コード例 #14
0
ファイル: queue-test.c プロジェクト: frelei/data-struct-c
int test_get_elements_queue(){
	int value1 = 1;
	int value2 = 2; 
	int value3 = 3;
	void *ptr;

	Queue *queue = create_queue(sizeof(int));
	add(queue, &value1);
	add(queue, &value2);
	add(queue, &value3);

	print_all_elements(queue);
	printf("\n-- Removing --\n");
	

	while(1){
		ptr = get(queue);
		if(ptr != NULL){		
			printf("removing: %d\n", *((int*)ptr));
		}else{	
			printf("Queue Empty\n");
			break;
		}
	}
	free(queue);
	return 0;
}
コード例 #15
0
ファイル: ntp_prio_q.c プロジェクト: qicny/freebsd
void
test_OneElementQueue(void) {
    queue* q = create_queue();

    TEST_ASSERT_NOT_NULL(q);

    element e = {"string", 3};
    element* e_ptr = debug_get_node(sizeof(element));
    enqueue(q, e_ptr);
    *e_ptr = e;

    TEST_ASSERT_FALSE(empty(q));
    TEST_ASSERT_NOT_NULL(queue_head(q));
    TEST_ASSERT_EQUAL(1, get_no_of_elements(q));

    element* e_ptr_returned = dequeue(q);

    TEST_ASSERT_NOT_NULL(e_ptr_returned);
    TEST_ASSERT_EQUAL_STRING(e_ptr_returned->str, "string");
    TEST_ASSERT_EQUAL_PTR(e_ptr_returned, e_ptr);
    TEST_ASSERT_EQUAL(0, get_no_of_elements(q));
    TEST_ASSERT_TRUE(empty(q));
    TEST_ASSERT_NULL(dequeue(q));

    destroy_queue(q);
}
コード例 #16
0
//driver code
int main()
{
    // Let cache can hold X pages
    unsigned int X = 4;
    Queue* q = create_queue( X );
 
    // Let Y different pages can be requested (pages to be
    // referenced are numbered from 0 to 9
    unsigned int Y = 10;
    Hash* hash = create_hash( Y );
 
    // Let us refer pages 1, 2, 3, 1, 4, 5
    reference_page( q, hash, 1);
    reference_page( q, hash, 2);
    reference_page( q, hash, 3);
    reference_page( q, hash, 1);
    reference_page( q, hash, 4);
    reference_page( q, hash, 5);
 
    // Let us print cache frames after the above referenced pages
    printf ("%d ", q->front->page_no);
    printf ("%d ", q->front->next->page_no);
    printf ("%d ", q->front->next->next->page_no);
    printf ("%d ", q->front->next->next->next->page_no);
 
    return 0;
}
コード例 #17
0
ファイル: test_file.c プロジェクト: nejmd/JPEG
int main()
{
        struct priority_queue *queue = create_queue(10);

        if (queue == NULL)
                printf("create_queue error\n");

        insert_queue(queue, 10, (struct huff_table*)10);
        insert_queue(queue, 11, (struct huff_table*)11);
        insert_queue(queue, 8, (struct huff_table*)8);
        insert_queue(queue, 3, (struct huff_table*)3);
        insert_queue(queue, 7, (struct huff_table*)7);
        insert_queue(queue, 15, (struct huff_table*)15);

        uint32_t priority = 0;
        struct huff_table *table = NULL;

        while (best_queue(queue, &priority, &table)) {

                printf("Table = %ld\n", (uint64_t)table);
                delete_queue(queue);
        }

        free_queue(queue);


        return EXIT_SUCCESS;
}
コード例 #18
0
void test_empty() {
  queue *q = create_queue();

  assert(empty(q));

  destroy_queue(q);
}
コード例 #19
0
ファイル: cqueue.c プロジェクト: BelfordZ/cAlgs
int
main() {
  queue_t *q;
  item_t t;
  int i,j;

  q = create_queue(3);
  i = 0;
  while( fscanf(stdin, "%d", &t) == 1 ) {
    if( ! t ) {
      if( ! i ) fprintf(stderr, "queue is alread empty\n");
      else {
	fprintf(stdout, "%d\n", dequeue(q));
	i--;
      }
    } else {
      enqueue(q, t);
      i++;
    }
  }

  for( j = 0; j < i; j++ ) {
    fprintf(stdout, "%d\n", dequeue(q));
  }

  destroy_queue(q);
  return 0;
}
コード例 #20
0
ファイル: graph.c プロジェクト: CodeR57/algorithms-1
static void BFS(struct graph_s *graph, struct vertex_s *s) {
    /* assumes graph is an adjacency list */
    int i;
    struct listnode_s *adj;
    struct vertex_s *u, *v;
    struct queue_s *Q;

    Q = create_queue(graph->num_vertices);

    for (i = 0; i < graph->num_vertices; ++i) {
        graph->vertices[i]->color = WHITE;
        graph->vertices[i]->distance = 0;
        graph->vertices[i]->predecessor = NULL;
    }

    s->color = GRAY;
    enqueue(Q, s);

    while (!is_empty(Q)) {
        u = dequeue(Q);
        for (adj = u->adj; adj; adj = adj->next) {
            v = adj->v;
            if (v->color == WHITE) {
                v->color = GRAY;
                v->distance = u->distance+1;
                v->predecessor = u;
                enqueue(Q, v);
            }
        }
        u->color = BLACK;
    }

    free(Q->vertices);
    free(Q);
}
コード例 #21
0
//Given a queue try to pull some items off
//Let's abuse the things we were given
//Use the queue as a list, order doesn't matter. Why rewrite code;
//Return queue of strings, and the number of items in there
queue_t * get_items(queue_t * queue, unsigned int num_items, unsigned int * num_returned)
{
	//Allocate a queue
	queue_t * ret_queue = create_queue();
	
	//Remove elements until reaching null or the number requested
	*num_returned = 0;
	#pragma omp critical
	{
		while(1)
		{
			//Try to remove an item
			queue_element_t * item = remove_from_queue(queue);
			if(item == NULL)
			{
				break;
			}
			
			//Add this item to the queue
			insert_in_queue(ret_queue, item);
			*num_returned = *num_returned +1;
			
			if(*num_returned >=num_items)
			{
				break;
			}
		}
	}
	
	
	//printf("Got %u/%u from queue\n", *num_returned, num_items);
	
	return ret_queue;
}
コード例 #22
0
ファイル: main.c プロジェクト: WinterLion/422projects
int main(int argc, char** argv) {
  // fifo_queue *q = create_queue();
 //    PCB pcb = {new, 0, 0, 0, 0, 0};
 //    enqueue(q, &pcb);
 //    PCB pcb2 = {new, 0, 0, 0, 0, 0};
 //    enqueue(q, &pcb2);
 //    printf("Hello");
//    pcb.next_pcb = &pcb2;
//    toString(&pcb);

    fifo_queue *queue = create_queue();

    PCB pcb = {new, 1, 23, 0, 23, 23, 23, 4, 5};
    PCB pcb2 = {new, 2, 34, 0, 34, 34, 34, 2, 1};

    enqueue(queue, &pcb);
    to_string_enqueue(queue);

    enqueue(queue, &pcb2);
    to_string_enqueue(queue);

    PCB_p pcb_removed = dequeue(queue);
    to_string_dequeue(queue, pcb_removed);

    pcb_removed = dequeue(queue);
    to_string_dequeue(queue, pcb_removed);

    testPQ();
    // pcb.next_pcb = &pcb2;
    // toString(&pcb);
    // toString(&pcb2);
    return (EXIT_SUCCESS);
}
コード例 #23
0
/*
 ******************************************************************************
 * dgadmin_rest_sync_main --                                                  *//**
 *
 * \brief This routine periodically starts sync circle.
 *
 * \param [in] pDummy	Not used.
 *
 * \retval None
 *
 *****************************************************************************/
static void dgadmin_rest_sync_main(UINT1 *pDummy)
{
    unsigned int 			listenEvent   = 0;
    unsigned int 			recvEvent     = 0;

    if (sem_give(gDgwySyncSemId) != OSW_OK) 
	{
		return;
    }
    if (create_queue("RSYNC", OSW_MAX_Q_MSG_LEN, 10, &gDgwySyncMsgId) != OSW_OK)
    {
        printf("%s:error when create queue\n",__FUNCTION__);
        return;
    }

    if (create_timer("RSTASK", DGWY_SYNC_TASK_TIMER_EVENT,
                     NULL, 0, &gDgwySyncTimerListId) != OSW_OK) 
    {
        printf("%s:error when create_timer\n",__FUNCTION__);
        return;
    }

    /* start the timer */
    start_timer(gDgwySyncTimerListId, DGADMIN_REST_SYNC_INTERVAL, 0);

    listenEvent = DGWY_SYNC_TASK_TIMER_EVENT;/* | DGWY_SYNC_TASK_MSG_EVENT; */

    log_info(ServiceUtilLogLevel,
             "INIT REST SYNC TASK ");

	while (1) 
    {
        if(recv_event(gDgwySyncTaskId, listenEvent, OSW_NO_WAIT, &recvEvent) == OSW_ERROR)
        {
            sleep(10);
            continue;
        }
    
        log_debug(ServiceUtilLogLevel,"recvEvent %d\n",
                  recvEvent);

        if(recvEvent & DGWY_SYNC_TASK_TIMER_EVENT)
        {
            if(g_dgw_role)
            {
                /* Try to be in sync with DMC */
                log_notice(ServiceUtilLogLevel,
                           "SYNC START: version %d\n", 
                           g_dgwconfig_curversion);
                dgadmin_rest_sync_process();
                log_notice(ServiceUtilLogLevel,
                           "SYNC END : version %d\n",
                           g_dgwconfig_curversion);
            }
            start_timer(gDgwySyncTimerListId, DGADMIN_REST_SYNC_INTERVAL, 0);
        }
        
    }
}
コード例 #24
0
ファイル: queue-test.c プロジェクト: frelei/data-struct-c
void test_isEmpty_full(){
	int value1 = 1;	
	Queue *queue = create_queue(sizeof(int));
	add(queue, &value1);
	if(!isEmpty(queue))
		printf("Success - fila not empty\n");
	free(queue);
}
コード例 #25
0
ファイル: threads.c プロジェクト: camieac/clabs
int main()
{
	Queue *q = create_queue(20);
	Argument *arg = create_argument(q,10);
	create_threads((void *)arg);
	printf("Complete\n");
  return(0);
}
コード例 #26
0
ファイル: packet_capture.c プロジェクト: Darma/trema
static void *
capture_main( void *args ) {
  UNUSED( args );

  info( "Starting packet capture ( interface_name = %s ).", interface_name );

  packet_queue = create_queue();
  pcap_t *cd = NULL;
  if ( packet_queue == NULL ) {
    error( "Failed to create packet queue." );
    goto error;
  }

  char errbuf[ PCAP_ERRBUF_SIZE ];
  bpf_u_int32 mask = 0;
  bpf_u_int32 net = 0;
  int ret = pcap_lookupnet( interface_name, &net, &mask, errbuf );
  if ( ret < 0 ) {
    error( "Failed to get netmask for device %s ( error = %s ).", interface_name, errbuf );
    net = 0;
    mask = 0;
  }

  cd = pcap_open_live( interface_name, UINT16_MAX, 1, 100, errbuf );
  if ( cd == NULL ) {
    error( "Failed to open network interface ( interface_name = %s, error = %s ).",
           interface_name, errbuf );
    goto error;
  }

  if ( filter_expression != NULL ) {
    struct bpf_program fp;
    ret = pcap_compile( cd, &fp, filter_expression, 0, net );
    if ( ret < 0 ) {
      error( "Failed to parse filter `%s' ( error = %s ).", filter_expression, pcap_geterr( cd ) );
      goto error;
    }
    ret = pcap_setfilter( cd, &fp );
    if ( ret < 0 ) {
      error( "Failed to set filter `%s' ( error = %s ).", filter_expression, pcap_geterr( cd ) );
      goto error;
    }
  }

  int dlt = pcap_datalink( cd );

  pcap_loop( cd, -1, handle_packet, ( u_char * ) &dlt );

error:
  if ( cd != NULL ) {
    pcap_close( cd );
  }
  if ( packet_queue != NULL ) {
    delete_queue( packet_queue );
  }

  return NULL;
}
コード例 #27
0
ファイル: thread_pool.c プロジェクト: hpc/mvapich2-cce
//struct thread_pool*  tp_init_thread_pool(struct thread_pool* pool,  int numthr, void*(func)(void*), char* name )
struct thread_pool *tp_create_thread_pool(int numthr, void *(func) (void *), char *name)
{
    struct thread_pool *pool;

    int i;

    if (numthr > MAX_THREAD_NUM) {
        printf("Error!! numthr %d > MAX-THREAD-NUM\n", numthr);
        return NULL;
    }
    /// alloc a thread-pool 
    pool = (struct thread_pool *) malloc(sizeof(struct thread_pool));
    if (!pool) {
        printf("Fail to create thrpool %s\n", name);
        return NULL;
    }
    memset(pool, 0, sizeof(struct thread_pool));

    // set thread-pool name 
    strncpy(pool->name, name, 15);
    pool->name[15] = 0;

    pool->num_threads = numthr;

    // work-queue associated with thread-pool
    pool->queue = create_queue("RR-queue");
    if (pool->queue == NULL) {
        error("Fail to create queue\n");
        goto err_out_1;
    }
    dump_queue(pool->queue);

    /// the mutex and bitmap is not necessary now...    
    pthread_mutex_init(&pool->mutex, NULL);

    /// now bitmap is no longer needed in a thread-pool, replaced by a work-queue 
    bmp_init(&pool->bitmap, numthr, 1); // initially all bits are "1": free
    //bmp_dump( &pool->bitmap);

    /// create the thread-pool
    for (i = 0; i < numthr; i++) {
        //sem_init( &pool->sem[i], 0, 0); // init the sem-count to be 0     
        //pool->arg1[i] = 0;
        //pool->arg2[i] = 0;
        if (pthread_create(&pool->thread[i], NULL, func, (void *) pool) != 0) {
            error("Error creating thread %d in pool %s\n", i, name);
        }
    }

    //dbg("tpool %s: init bitmap= %s\n", pool->name, int_to_binary(pool->bitmap) );
    printf("Have created tpool %s: thr-num = %d\n", pool->name, pool->num_threads);

    return pool;

  err_out_1:
    tp_destroy_thread_pool(pool);
    return NULL;
}
コード例 #28
0
int main (int argc, char **argv)
{
	if ( argc != 2){
		printf ("usage: %s number_of_details\n", argv[0]);
		return 2;
	} 
	// получаем очередь сообщений для всех процессов.
	create_queue();
	/* создаем процесс - закрутчик гаек. */
	create_nipple_worker( 0);
	create_nipple_worker( 1);
	/* создаем процесс - закрутчик винтов. */
	create_screw_worker( 2);
	message mbuf;
	// cnt раз подадим деталь на тиски.
	int cnt = atoi (argv[1]);
	printf (" %d details\n", cnt);
	do{
		//сообщим всем процессам - что деталь установлена. 
		//(поместим _три_ сообщения в очередь)
		int i;
		printf("send new detail, last #%d\n", cnt-1);
		for( i = 0; i < NUM_OF_WORKERS; i++){
			message mbuf;
			mbuf.mtype = NEW_DETAIL_FOR_1 + i;
			//new_detail_for_1
			//new_detail_for_2
			//new_detail_for_3 =)
			if ( msgsnd ( msqid, &mbuf, 2, IPC_NOWAIT) < 0){
				perror ("msgsnd");
				return 1;
			}
		}
		// Проверим, все-ли закончили свою работу?
		if ( msgrcv (msqid, &mbuf, 2, ONE_NIPPLE_INSTALLED, 0) < 0 ){
			perror ("msgrcv");
			return 1;
		}
		if ( msgrcv (msqid, &mbuf, 2, ONE_NIPPLE_INSTALLED, 0) < 0 ){
			perror ("msgrcv");
			return 1;
		}
		if ( msgrcv (msqid, &mbuf, 2, ONE_SCREW_INSTALLED, 0) < 0 ){
			perror ("msgrcv");
			return 1;
		}
	} while (--cnt > 0);
	
	//удаляем очередь
	if ( msgctl (msqid, IPC_RMID, NULL) < 0 ){
		perror ("queue delete:");
		return 1;
	}
	printf("finished\n");

	return 0;
}
コード例 #29
0
priority_queue_p create_priority_queue() {
    int i;
    priority_queue_p pq  = malloc(sizeof(fifo_queue_p) * NumberOfPriorities);
    for (i = 0; i < NumberOfPriorities; i++) {
        pq->MainArray[i] = create_queue();    
    }
    pq->size = 0;
    return pq;
}
コード例 #30
0
ファイル: toxav.c プロジェクト: 9cat/ProjectTox-Core
/**
 * @brief Must be call before any RTP transmission occurs.
 *
 * @param av Handler.
 * @return int
 * @retval 0 Success.
 * @retval ToxAvError On error.
 */
int toxav_prepare_transmission ( ToxAv *av, int32_t call_index, ToxAvCodecSettings *codec_settings, int support_video )
{
    if ( !av->msi_session || av->msi_session->max_calls <= call_index || !av->msi_session->calls[call_index] ) {
        /*fprintf(stderr, "Error while starting audio RTP session: invalid call!\n");*/
        return ErrorInternal;
    }

    CallSpecific *call = &av->calls[call_index];

    call->crtps[audio_index] =
        rtp_init_session(
            type_audio,
            av->messenger,
            av->msi_session->calls[call_index]->peers[0],
            av->msi_session->calls[call_index]->key_peer,
            av->msi_session->calls[call_index]->key_local,
            av->msi_session->calls[call_index]->nonce_peer,
            av->msi_session->calls[call_index]->nonce_local);


    if ( !call->crtps[audio_index] ) {
        /*fprintf(stderr, "Error while starting audio RTP session!\n");*/
        return ErrorStartingAudioRtp;
    }


    if ( support_video ) {
        call->crtps[video_index] =
            rtp_init_session (
                type_video,
                av->messenger,
                av->msi_session->calls[call_index]->peers[0],
                av->msi_session->calls[call_index]->key_peer,
                av->msi_session->calls[call_index]->key_local,
                av->msi_session->calls[call_index]->nonce_peer,
                av->msi_session->calls[call_index]->nonce_local);


        if ( !call->crtps[video_index] ) {
            /*fprintf(stderr, "Error while starting video RTP session!\n");*/
            return ErrorStartingVideoRtp;
        }
    }

    if ( !(call->j_buf = create_queue(codec_settings->jbuf_capacity)) ) return ErrorInternal;

    call->cs = codec_init_session(codec_settings->audio_bitrate,
                                  codec_settings->audio_frame_duration,
                                  codec_settings->audio_sample_rate,
                                  codec_settings->audio_channels,
                                  codec_settings->video_width,
                                  codec_settings->video_height,
                                  codec_settings->video_bitrate);

    return call->cs ? ErrorNone : ErrorInternal;
}