示例#1
0
static int
do_test (void)
{
  stack_t ss;
  ss.ss_sp = malloc (2 * SIGSTKSZ);
  if (ss.ss_sp == NULL)
    {
      puts ("failed to allocate alternate stack");
      return 1;
    }
  ss.ss_flags = 0;
  ss.ss_size = 2 * SIGSTKSZ;
  if (sigaltstack (&ss, NULL) < 0)
    {
      printf ("sigaltstack failed %m\n");
      return 1;
    }

  if (pthread_barrier_init (&b, NULL, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  struct sigaction sa;
  sa.sa_handler = sh;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = 0;

  if (sigaction (SIGHUP, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      return 1;
    }

  puts ("sa_flags = 0 test");
  if (do_one_test ())
    return 1;

  sa.sa_handler = sh;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = SA_ONSTACK;

  if (sigaction (SIGHUP, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      return 1;
    }

  puts ("sa_flags = SA_ONSTACK test");
  if (do_one_test ())
    return 1;

  sa.sa_sigaction = (void (*)(int, siginfo_t *, void *)) sh;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = SA_SIGINFO;

  if (sigaction (SIGHUP, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      return 1;
    }

  puts ("sa_flags = SA_SIGINFO test");
  if (do_one_test ())
    return 1;

  sa.sa_sigaction = (void (*)(int, siginfo_t *, void *)) sh;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = SA_SIGINFO | SA_ONSTACK;

  if (sigaction (SIGHUP, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      return 1;
    }

  puts ("sa_flags = SA_SIGINFO|SA_ONSTACK test");
  if (do_one_test ())
    return 1;

  return 0;
}
示例#2
0
TEST (PthreadTest, All) {
    // At one point we had a bug in that tatas lock relied on
    // the impelemtation's sizeof pthread_t
    tatas_lock lock; 
    cout << "Sizes: " << endl;
    cout << "pthread_t: " << sizeof(pthread_t) << endl;
    cout << "lock._holder: " << sizeof(lock._holder) << endl;
    cout << "lock._holder.bits: " << sizeof(lock._holder.bits) << endl;
    EXPECT_EQ(sizeof(lock._holder.handle), sizeof(lock._holder.bits));
    cout << endl;

    int threads = 2;

        /* Determine how many threads we can create in this process
         * First, see if there is a limit in <limits.h>
         *   This doesn't have to be defined if the value is determined by
         *   available memeory.
         * Second, see if there is a limit available with sysconf.
         *   This does have to be define by a POSIX 1003.1c-1995-compliant system.
         * */

        long m;
    cout << "_POSIX_VERSION/_SC_VERSION ----------------------------- " <<endl;
#ifdef _POSIX_VERSION
    cout << "POSIX_VERSION " << _POSIX_VERSION << endl;
#endif
#ifdef _SC_VERSION
        m = sysconf(_SC_VERSION);
    cout << "sysconf: _SC_VERSION " << 
                        _SC_VERSION << endl;
#endif

    cout << "_POSIX2_VERSION/_SC_2_VERSION ----------------------------- " <<endl;
#ifdef _POSIX2_VERSION
    cout << "POSIX2_VERSION " << _POSIX2_VERSION << endl;
#endif
#ifdef _SC_2_VERSION
        m = sysconf(_SC_2_VERSION);
    cout << "sysconf: _SC_2_VERSION " << 
                        _SC_2_VERSION << endl;
#endif

    cout << "_XOPEN_VERSION/_SC_XOPEN_VERSION ----------------------------- " <<endl;
#ifdef _XOPEN_VERSION
    cout << "XOPEN_VERSION " << _XOPEN_VERSION << endl;
#endif
#ifdef _SC_XOPEN_VERSION
        m = sysconf(_SC_XOPEN_VERSION);
    cout << "sysconf: _SC_XOPEN_VERSION " << 
                        _SC_XOPEN_VERSION << endl;
#endif

    cout << "_POSIX_THREADS/_SC_THREADS ----------------------------- " <<endl;
#ifdef _POSIX_THREADS
    cout << "_POSIX_THREADS " << _POSIX_THREADS << endl;
#endif
#ifdef _SC_THREADS
        m = sysconf(_SC_THREADS);
    cout << "sysconf: _SC_THREADS " << 
                        _SC_THREADS << endl;
#endif

    cout << "_POSIX_THREAD_ATTR_STACKSIZE/_SC_THREAD_ATTR_STACKSIZE ----------------------------- " <<endl;
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
    cout << "POSIX_THREAD_ATTR_STACKSIZE " << _POSIX_THREAD_ATTR_STACKSIZE << endl;
#endif
#ifdef _SC_THREAD_ATTR_STACKSIZE
        m = sysconf(_SC_THREAD_ATTR_STACKSIZE);
    cout << "sysconf: _SC_THREAD_ATTR_STACKSIZE " << 
                        _SC_THREAD_ATTR_STACKSIZE << endl;
#endif

    cout << "_POSIX_THREAD_ATTR_STACKADDR/_SC_THREAD_ATTR_STACKADDR ----------------------------- " <<endl;
#ifdef _POSIX_THREAD_ATTR_STACKADDR
    cout << "POSIX_THREAD_ATTR_STACKADDR " << _POSIX_THREAD_ATTR_STACKADDR << endl;
#endif
#ifdef _SC_THREAD_ATTR_STACKADDR
        m = sysconf(_SC_THREAD_ATTR_STACKADDR);
    cout << "sysconf: _SC_THREAD_ATTR_STACKADDR " << 
                        _SC_THREAD_ATTR_STACKADDR << endl;
#endif

#ifdef _POSIX_BARRIERS
    cout << "POSIX_BARRIERS " << _POSIX_BARRIERS << endl;
#endif
#ifdef _POSIX_READER_WRITER_LOCKS
    cout << "POSIX_READER_WRITER_LOCKS " << _POSIX_READER_WRITER_LOCKS << endl;
#endif

#ifdef _POSIX_THREAD_THREADS_MAX
    cout << "POSIX_THREAD_THREADS_MAX " << _POSIX_THREAD_THREADS_MAX << endl;
#endif

#ifdef PTHREAD_THREADS_MAX
        threads = PTHREADS_MAX;
    cout << "limits.h: maximum pthreads per process is " << 
                        threads << endl;
#else
    cout 
        << "limits.h: maximum pthreads per process is not defined." 
        << endl;
#endif
#ifdef _SC_THREAD_THREADS_MAX
        m = sysconf(_SC_THREAD_THREADS_MAX);
    cout << "limits.h: maximum pthreads per process is " << 
                        m << endl;
        threads = int(m);
#else
    cout 
        << "NOT COMPLIIANT: sysconf: maximum _SC_PTHREAD_THREADS_MAX is not defined." 
        << endl;
#endif

        // create and fork as many threads as the system will allow,

#ifdef TEST_FIND_PTHREAD_RUNTIMEMAX
        threads=0;
    while(true) {
                threads++;
                // pthread_attr_t attr;
                pthread_t thr;
                int e= pthread_create(&thr, NULL, dummy, NULL);
                if(e!=0) {
                        if(e==EAGAIN) {
                                cout << "runtime: maximum pthreads " << threads << endl;
                                break;
                        }
                        perror("perror ");
                        cout << "ERROR " << e << endl;
                        cout << "threads " << threads << endl;
                        break;
                }
    }
        // On RHEL 5 I got 32748 with the runtime test despite having
        // the stated limit of POSIX_THREAD_THREADS_MAX of 64.
#endif

        threads=2;
        // They all wait on this barrier.
    pthread_barrier_init(&b, NULL, threads+1);
    sthread_t **t = new sthread_t *[threads];

    for (int i = 0; i < threads; i++)
        t[i] = new simple_thread_t();

    for (int i = 0; i < threads; i++)
        EXPECT_TRUE(t[i] != NULL);

    for (int i = 0; i < threads; i++)
        EXPECT_FALSE(t[i]->fork().is_error());

    pthread_barrier_wait(&b);

    for (int i = 0; i < threads; i++)
        EXPECT_FALSE(t[i]->join().is_error());

    pthread_barrier_destroy(&b);
    
    delete[] t;
}
示例#3
0
static int
do_test (void)
{
  if (pthread_barrier_init (&bar, NULL, 3) != 0)
    {
      puts ("barrier_init failed");
      exit (1);
    }

  pthread_attr_t a;

  if (pthread_attr_init (&a) != 0)
    {
      puts ("attr_init failed");
      exit (1);
    }

  if (pthread_attr_setstacksize (&a, 1 * 1024 * 1024) != 0)
    {
      puts ("attr_setstacksize failed");
      return 1;
    }

  pthread_t th[2];

  if (pthread_create (&th[0], &a, tf, NULL) != 0)
    {
      puts ("1st create failed");
      exit (1);
    }

  if (pthread_attr_setdetachstate (&a, PTHREAD_CREATE_DETACHED) != 0)
    {
      puts ("attr_setdetachstate failed");
      exit (1);
    }

  if (pthread_create (&th[1], &a, tf, NULL) != 0)
    {
      puts ("1st create failed");
      exit (1);
    }

  if (pthread_attr_destroy (&a) != 0)
    {
      puts ("attr_destroy failed");
      exit (1);
    }

  if (pthread_detach (th[0]) != 0)
    {
      puts ("could not detach 1st thread");
      exit (1);
    }

  int err = pthread_detach (th[0]);
  if (err == 0)
    {
      puts ("second detach of 1st thread succeeded");
      exit (1);
    }
  if (err != EINVAL)
    {
      printf ("second detach of 1st thread returned %d, not EINVAL\n", err);
      exit (1);
    }

  err = pthread_detach (th[1]);
  if (err == 0)
    {
      puts ("detach of 2nd thread succeeded");
      exit (1);
    }
  if (err != EINVAL)
    {
      printf ("detach of 2nd thread returned %d, not EINVAL\n", err);
      exit (1);
    }

  exit (0);
}
示例#4
0
int
main()
{
  int i;
  int fail = 0;
  pthread_t thread[NUM_THREADS];

  assert(pthread_barrier_init(&startBarrier, NULL, NUM_THREADS/2) == 0);

  for (i = 1; i < NUM_THREADS/2; i++)
    {
      accesscount[i] = thread_set[i] = thread_destroyed[i] = 0;
      assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0);
    }

  /*
   * Here we test that existing threads will get a key created
   * for them.
   */
  assert(pthread_key_create(&key, destroy_key) == 0);

  (void) pthread_barrier_wait(&startBarrier);

  /*
   * Test main thread key.
   */
  accesscount[0] = 0;
  setkey((void *) &accesscount[0]);

  /*
   * Here we test that new threads will get a key created
   * for them.
   */
  for (i = NUM_THREADS/2; i < NUM_THREADS; i++)
    {
      accesscount[i] = thread_set[i] = thread_destroyed[i] = 0;
      assert(pthread_create(&thread[i], NULL, mythread, (void *)&accesscount[i]) == 0);
    }

  /*
   * Wait for all threads to complete.
   */
  for (i = 1; i < NUM_THREADS; i++)
    {
	assert(pthread_join(thread[i], NULL) == 0);
    }

  assert(pthread_key_delete(key) == 0);

  assert(pthread_barrier_destroy(&startBarrier) == 0);

  for (i = 1; i < NUM_THREADS; i++)
    {
	/*
	 * The counter is incremented once when the key is set to
	 * a value, and again when the key is destroyed. If the key
	 * doesn't get set for some reason then it will still be
	 * NULL and the destroy function will not be called, and
	 * hence accesscount will not equal 2.
	 */
	if (accesscount[i] != 2)
	  {
	    fail++;
	    fprintf(stderr, "Thread %d key, set = %d, destroyed = %d\n",
			i, thread_set[i], thread_destroyed[i]);
	  }
    }

  fflush(stderr);

  return (fail);
}
示例#5
0
/* The main test function. */
int main( int argc, char *argv[] )
{
	int ret = 0;
	pthread_t tcontrol, tchange;
	pthread_barrier_t bar;

	/* Initialize output routine */
	output_init();

	ret = pthread_barrier_init( &bar, NULL, 2 );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to init barrier" );
	}

	/* Create the controler thread */
	ret = pthread_create( &tcontrol, NULL, controler, &bar );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "thread creation failed" );
	}

	/* Now create the changer thread */
	ret = pthread_create( &tchange, NULL, changer, &tcontrol );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "thread creation failed" );
	}

	/* wait until the changer finishes */
	ret = pthread_join( tchange, NULL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to join the thread" );
	}


	/* let the controler control */
	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}


	ret = pthread_join( tcontrol, NULL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to join the thread" );
	}

	ret = pthread_barrier_destroy( &bar );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "barrier destroy failed" );
	}

	PASSED;
}
示例#6
0
文件: pgrep_dummy.c 项目: sizur/c-rrb
int main(int argc, char *argv[]) {
    // CLI argument parsing
    if (argc != 4) {
        fprintf(stderr, "Expected 3 arguments, got %d\nExiting...\n", argc - 1);
        exit(1);
    }
    else {
        char *end;
        uint32_t thread_count = (uint32_t) strtol(argv[1], &end, 10);
        if (*end) {
            fprintf(stderr, "Error, expects first argument to be a power of two,"
                    " was '%s'.\n", argv[1]);
            exit(1);
        }
        if (!(thread_count && !(thread_count & (thread_count - 1)))) {
            fprintf(stderr, "Error, first argument must be a power of two, not %d.\n",
                    thread_count);
            exit(1);
        }
        fprintf(stderr, "Looking for '%s' in file %s using %d threads...\n",
                argv[2], argv[3], thread_count);

        char *search_term = argv[2];

        FILE *fp;
        long file_size;
        char *buffer;
        fp = fopen(argv[3], "rb");
        if (!fp) {
            perror(argv[1]);
            exit(1);
        }
        fseek(fp, 0, SEEK_END);
        file_size = ftell(fp);
        rewind(fp);

        buffer = malloc(file_size + 1);
        if (!buffer) {
            fclose(fp);
            fprintf(stderr, "Cannot allocate buffer for file (probably too large).\n");
            exit(1);
        }
        buffer[file_size] = 0;

        if (1 != fread(buffer, file_size, 1, fp)) {
            fclose(fp);
            free(buffer);
            fprintf(stderr, "Entire read failed.\n");
            exit(1);
        }
        else {
            fclose(fp);
        }


        // Find all lines
        pthread_t *tid = malloc(thread_count * sizeof(pthread_t));
        LineSplitArgs *lsa = malloc(thread_count * sizeof(LineSplitArgs));
        uint32_t *intervals = malloc(thread_count * sizeof(uint32_t));
        struct timespec time_start, time_stop;
        long long nanoseconds_elapsed;

        for (uint32_t i = 0; i < thread_count; i++) {
            LineSplitArgs arguments =
            {   .buffer = buffer, .file_size = (uint32_t) file_size,
                .own_tid = i, .thread_count = thread_count,
                .intervals = intervals
            };
            lsa[i] = arguments;
        }

        clock_gettime(CLOCK_MONOTONIC, &time_start);
        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_create(&tid[i], NULL, &split_to_lines, (void *) &lsa[i]);
        }

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_join(tid[i], NULL);
        }
        clock_gettime(CLOCK_MONOTONIC, &time_stop);
        nanoseconds_elapsed = (time_stop.tv_sec - time_start.tv_sec) * 1000000000LL;
        nanoseconds_elapsed += (time_stop.tv_nsec - time_start.tv_nsec);

        long long line_split = nanoseconds_elapsed;

        free(lsa);

        // Concatenate work
        ConcatArgs *ca = malloc(thread_count * sizeof(ConcatArgs));
        pthread_barrier_t *barriers = malloc(thread_count * sizeof(pthread_barrier_t));

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_barrier_init(&barriers[i], NULL, 2);
            ConcatArgs args = {.own_tid = i, .thread_count = thread_count,
                               .intervals = intervals, .barriers = barriers
                              };
            ca[i] = args;
        }

        clock_gettime(CLOCK_MONOTONIC, &time_start);
        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_create(&tid[i], NULL, &concatenate_arrays, (void *) &ca[i]);
        }

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_join(tid[i], NULL);
        }
        clock_gettime(CLOCK_MONOTONIC, &time_stop);
        nanoseconds_elapsed = (time_stop.tv_sec - time_start.tv_sec) * 1000000000LL;
        nanoseconds_elapsed += (time_stop.tv_nsec - time_start.tv_nsec);

        long long line_concat = nanoseconds_elapsed;

        uint32_t line_count = intervals[0];

        // Actually find lines (done here, to avoid cache modification)
        IntervalArray *lines = find_lines(buffer, (uint32_t) file_size, thread_count);

        // Found all lines, now onto searching in each list

        fprintf(stderr, "%d newlines\n", line_count);

        FilterArgs *fa = malloc(thread_count * sizeof(FilterArgs));
        // Reuse intervals array

        for (uint32_t i = 0; i < thread_count; i++) {
            FilterArgs arguments =
            {   .buffer = buffer, .search_term = search_term,
                .lines = lines, .intervals = intervals,
                .own_tid = i, .thread_count = thread_count
            };
            fa[i] = arguments;
        }

        clock_gettime(CLOCK_MONOTONIC, &time_start);
        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_create(&tid[i], NULL, &filter_by_term, (void *) &fa[i]);
        }

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_join(tid[i], NULL);
        }

        clock_gettime(CLOCK_MONOTONIC, &time_stop);
        nanoseconds_elapsed = (time_stop.tv_sec - time_start.tv_sec) * 1000000000LL;
        nanoseconds_elapsed += (time_stop.tv_nsec - time_start.tv_nsec);

        long long search_lines = nanoseconds_elapsed;

        // Concatenate work
        // Reuse concat args and barriers

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_barrier_init(&barriers[i], NULL, 2);
            ConcatArgs args = {.own_tid = i, .thread_count = thread_count,
                               .intervals = intervals, .barriers = barriers
                              };
            ca[i] = args;
        }

        clock_gettime(CLOCK_MONOTONIC, &time_start);
        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_create(&tid[i], NULL, &concatenate_arrays, (void *) &ca[i]);
        }

        for (uint32_t i = 0; i < thread_count; i++) {
            pthread_join(tid[i], NULL);
        }

        clock_gettime(CLOCK_MONOTONIC, &time_stop);
        nanoseconds_elapsed = (time_stop.tv_sec - time_start.tv_sec) * 1000000000LL;
        nanoseconds_elapsed += (time_stop.tv_nsec - time_start.tv_nsec);

        long long search_concat = nanoseconds_elapsed;

        fprintf(stderr, "%d hits\n", intervals[0]);

        printf("%lld %lld %lld %lld %lld\n", line_split, line_concat,
               search_lines, search_concat,
               line_split + line_concat + search_lines + search_concat);

        interval_array_destroy(lines);
        free(intervals);
        free(buffer);
        free(ca);
        free(barriers);
        exit(0);
    }

}

// Unmeasured stuff, to actually FIND the lines we're parallelizing over
static IntervalArray* find_lines(char* buffer, uint32_t file_size, uint32_t thread_count) {
    pthread_t *tid = malloc(thread_count * sizeof(pthread_t));
    LineSplitArgsUnmeasured *lsa = malloc(thread_count * sizeof(LineSplitArgsUnmeasured));
    IntervalArray **intervals = malloc(thread_count * sizeof(IntervalArray *));

    for (uint32_t i = 0; i < thread_count; i++) {
        LineSplitArgsUnmeasured arguments =
        {   .buffer = buffer, .file_size = (uint32_t) file_size,
            .own_tid = i, .thread_count = thread_count,
            .intervals = intervals
        };
        lsa[i] = arguments;
    }

    for (uint32_t i = 0; i < thread_count; i++) {
        pthread_create(&tid[i], NULL, &split_to_lines_unmeasured, (void *) &lsa[i]);
    }

    for (uint32_t i = 0; i < thread_count; i++) {
        pthread_join(tid[i], NULL);
    }
    free(lsa);

    // Concatenate work
    ConcatArgsUnmeasured *ca = malloc(thread_count * sizeof(ConcatArgsUnmeasured));
    pthread_barrier_t *barriers = malloc(thread_count * sizeof(pthread_barrier_t));

    for (uint32_t i = 0; i < thread_count; i++) {
        pthread_barrier_init(&barriers[i], NULL, 2);
        ConcatArgsUnmeasured args = {.own_tid = i, .thread_count = thread_count,
                                     .intervals = intervals, .barriers = barriers
                                    };
        ca[i] = args;
    }

    for (uint32_t i = 0; i < thread_count; i++) {
        pthread_create(&tid[i], NULL, &concatenate_arrays_unmeasured, (void *) &ca[i]);
    }

    for (uint32_t i = 0; i < thread_count; i++) {
        pthread_join(tid[i], NULL);
    }
    IntervalArray *lines = intervals[0];
    free(tid);
    free(barriers);
    free(ca);
    free(intervals);
    return lines;
}


static void* split_to_lines_unmeasured(void *void_input) {
    LineSplitArgsUnmeasured *lsa = (LineSplitArgsUnmeasured *) void_input;
    const char *buffer = lsa->buffer;
    const uint32_t own_tid = lsa->own_tid;
    const uint32_t file_size = lsa->file_size;
    const uint32_t thread_count = lsa->thread_count;
    IntervalArray **intervals = lsa->intervals;

    // calculate the interval to compute for
    uint32_t partition_size = file_size / thread_count;
    uint32_t from = partition_size * own_tid;
    uint32_t to = partition_size * (own_tid + 1);
    if (own_tid + 1 == thread_count) {
        to = file_size;
    }

    // find the lines
    IntervalArray *lines = interval_array_create();

    // rewind to start of line
    uint32_t line_start = from;
    while (0 < line_start && lsa->buffer[line_start] != '\n') {
        line_start--;
    }
    // find and collect lines
    for (uint32_t i = from; i < to; i++) {
        if (buffer[i] == '\n') {
            Interval interval = {.from = line_start, .to = i};
            interval_array_add(lines, interval);
            line_start = i + 1;
        }
    }
示例#7
0
文件: main.c 项目: am-ivanov/le2d
int main(int argc, char *argv[])
{
	if (argc != 5) {
		printf("Usage: %s nx ny steps threads.\n", argv[0]);
		return 1;
	}
	int i, ti;
	le_point2 n = {atoi(argv[1]), atoi(argv[2])};
	int steps = atoi(argv[3]);
	int max_threads = atoi(argv[4]);
	le_task task;
	le_material mat;
	le_vec2 h = {1.0, 1.0};
	real dt = 0.3;
	le_vec2 center = {n.x / 2, n.y / 2};
	char name[1000];

	double t;
	unsigned long cc;
	
	/* pthread variables */
	pthread_t threads[NUM_THREADS];
	st_pthread data[NUM_THREADS];
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
	/* end of pthread variables */

	le_init_material(2.0, 1.0, 1.5, &mat);
	task.max_threads = max_threads;
	task.steps = steps;
	le_init_task(&task, dt, h, mat, n);
	le_set_ball(&task, center, 10.0, 1.0);

	pthread_barrier_init(&b, NULL, max_threads);
	
	cc = getCC();
	t = timer();
	
	for(ti = 0; ti < max_threads; ti++) {		
		data[ti].task = &task;
		data[ti].thread_num = ti;
		int rc = pthread_create(&(threads[ti]), &attr, le_step, (void *)(&(data[ti])));
		assert(!rc);
	}
	for(ti = 0; ti < max_threads; ti++) {
		void *st;
		int rc = pthread_join(threads[ti], &st);
		assert(!rc);;
	}
	
	t = timer() - t;
	cc = getCC() - cc;
	
	pthread_barrier_destroy(&b);
	
	printf("%d %d %d %f ", n.x, n.y, steps, t);
	
	le_save_task(&task, "result.vtk");

	le_free_task(&task);
	pthread_exit(NULL);
}
示例#8
0
static int
do_test (void)
{
  if (pthread_barrier_init (&b, NULL, N + 1) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  pthread_mutex_lock (&mut);

  int i, j, err;
  pthread_t th[N];
  for (i = 0; i < N; ++i)
    if ((err = pthread_create (&th[i], NULL, tf, NULL)) != 0)
      {
	printf ("cannot create thread %d: %s\n", i, strerror (err));
	return 1;
      }

  for (i = 0; i < ROUNDS; ++i)
    {
      pthread_cond_wait (&cond2, &mut);

      if (i & 1)
        pthread_mutex_unlock (&mut);

      if (i & 2)
	pthread_cond_broadcast (&cond);
      else if (i & 4)
	for (j = 0; j < N; ++j)
	  pthread_cond_signal (&cond);
      else
	{
	  for (j = 0; j < (i / 8) % N; ++j)
	    pthread_cond_signal (&cond);
	  pthread_cond_broadcast (&cond);
	}

      if ((i & 1) == 0)
        pthread_mutex_unlock (&mut);

      err = pthread_cond_destroy (&cond);
      if (err)
	{
	  printf ("pthread_cond_destroy failed: %s\n", strerror (err));
	  return 1;
	}

      /* Now clobber the cond variable which has been successfully
         destroyed above.  */
      memset (&cond, (char) i, sizeof (cond));

      err = pthread_barrier_wait (&b);
      if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD)
	{
	  puts ("parent: barrier_wait failed");
	  return 1;
	}

      pthread_mutex_lock (&mut);

      err = pthread_barrier_wait (&b);
      if (err != 0 && err != PTHREAD_BARRIER_SERIAL_THREAD)
	{
	  puts ("parent: barrier_wait failed");
	  return 1;
	}

      count = 0;
      err = pthread_cond_init (&cond, NULL);
      if (err)
	{
	  printf ("pthread_cond_init failed: %s\n", strerror (err));
	  return 1;
	}
    }

  for (i = 0; i < N; ++i)
    if ((err = pthread_join (th[i], NULL)) != 0)
      {
	printf ("failed to join thread %d: %s\n", i, strerror (err));
	return 1;
      }

  puts ("done");

  return 0;
}
int main(int argc, char **argv) { 
   struct timeval start, end;

   //Read partition file
   char *dot = strrchr(argv[2], '.');
   if (!dot || dot == argv[2]) dot = "";
   else dot = dot + 1;
   
   int partitionCount = 0;
   //determine the number of partitions
   if (isdigit(dot[0])) {
      partitionCount = atoi(dot);
   } else {
      printf("INVALID PARTITION FILE\n");
      exit(1);
   }

   max_threads = partitionCount;
   pthread_t p_threads[max_threads];
   pthread_attr_t attr;
   pthread_attr_init(&attr);
   pthread_mutex_init(&sumLock, NULL);

   pthread_barrier_init(&barr, NULL, max_threads);

   FILE *pFile = fopen(argv[1], "r");
   if (pFile==NULL) {
      printf("File error");
      fputs ("File error", stderr); 
      exit(1);
   }

   int size;
   fseek (pFile, 0, SEEK_END);
   size = ftell(pFile);
   rewind (pFile);

   int i = 0;
   char st[20];
   int readRowsPtrs = 0;
   long int* rownum = (long int *) malloc(size * sizeof(long int));

   printf("READING LAST LINE\n");
   while (fscanf(pFile, "%20s", st) != EOF) {
      if (readRowsPtrs == 1) {
         long int v;
         v = strtol(st, NULL, 0);
         rownum[i] = v;
         i++;
      }

      if (strcmp(st, "row_ptrs:") == 0) {
         readRowsPtrs = 1;
      }
   }
   rewind(pFile);
   printf("LAST LINE READ\n");

   struct row matrixdata;
   matrixdata.rowary = malloc(i * sizeof(rowData));
   matrixdata.rcount = i-1;
   
   int *outGoingEdgeCount = (int *) malloc(matrixdata.rcount * sizeof(int));

   int c;
   for (c=0; c < matrixdata.rcount; c++) { //i is the total amount of rows in the matrix
      long int rowSize;
      rowSize = rownum[c+1] - rownum[c];

      matrixdata.rowary[c].values = malloc(rowSize * sizeof(double));
      matrixdata.rowary[c].col = malloc(rowSize * sizeof(long int));
      matrixdata.rowary[c].vcount = rowSize;

      outGoingEdgeCount[c] = 0;
   }
   free(rownum);

   i = 0;
   c = 0;      //Matrix row incrementor
   char str[20];
   int newline = 0;
   char ch;
   rewind(pFile);

   printf("READING col_inds LINE\n");
   readRowsPtrs = 0;
   while (fscanf(pFile, "%20s", st) != EOF) {
      if (strcmp(st, "row_ptrs:") == 0) {
         break;
      }

      if (readRowsPtrs == 1) {
         int v;
         v = strtol(st, NULL, 0);
         outGoingEdgeCount[v] = outGoingEdgeCount[v] + 1;
      }

      if (strcmp(st, "col_inds:") == 0) {
         readRowsPtrs = 1;
      }
   }
   rewind(pFile);
   printf("col_inds LINE READ\n");

   printf("POPULATING MATRIX\n");
   while (fscanf(pFile, "%s%c", str, &ch) != EOF && newline < 3) {
      if(isdigit(str[0])) {
         if(i == matrixdata.rowary[c].vcount) {
            i = 0;
            c++;
         }
         if(c > matrixdata.rcount) {
            printf("Number of rows is more than allocated rows\n");
            exit(1);
         }

         //Determine what the current values represent
         if(newline == 1) {
            //Convert String values to double strtod 
            double v;
            v = strtod(str, NULL);
            matrixdata.rowary[c].values[i] = v;
         } else if (newline == 2) { //if(strcmp(header, "col_inds:") == 0) {
            //Convert String values to int strtol
            long int v;
            v = strtol(str, NULL, 0);
            matrixdata.rowary[c].col[i] = v;
            matrixdata.rowary[c].values[i] = matrixdata.rowary[c].values[i]/outGoingEdgeCount[v];
         } 
         i++; //Counts the total number of nodes
      } else {
         c=0;
         i=0;
         newline++;
      }
      
      if (ch == '\n') { //END OF LINE
         c = 0;
         i = 0;
      }
   }

   printf("END OF FILE\n");
   fclose(pFile);
   printf("FILE CLOSED\n");
   free(outGoingEdgeCount);

   //Array of linkedlists. Array determines partition location. Linkedlist is nodes belonging to partition
   struct pNode *partitionArray = malloc(partitionCount * sizeof(struct pNode));
   int *sizeofEachPartition= (int *) malloc(partitionCount * sizeof(int));

   //Initialize linked list
   for (i=0;i<partitionCount;i++){
      partitionArray[i].next = 0;
      partitionArray[i].last = 0;
      partitionArray[i].val = -1;
      sizeofEachPartition[i] = 0;
   }

   //Open partition file. Parameter 2 is partition file
   FILE *partFile = fopen(argv[2], "r");
   if (partFile==NULL) {
      printf("File error");
      fputs ("File error", stderr); 
      exit(1);
   }

   i=0;
   c=0;
   //Read Partition file and store where rows should be broken up into
   //c is the partition location. i is the node or line number. 
   printf("READING PARTITION FILE\n");
   while (fscanf(partFile, "%d", &c) != EOF) {
      //c is the processor number
      //Go to processor linked list
      struct pNode *newNode = &partitionArray[c];
      struct pNode *firstNode = &partitionArray[c];
      

      if (firstNode->last != 0) {
         //Go to last node
         newNode = firstNode->last;
      } 
      if (newNode->val != -1) {
         if (newNode != 0) {
            while (newNode->next != 0){
               newNode = newNode->next;
            }
         }

         //Add new node to linked list
         newNode->next = malloc(sizeof(struct pNode));
         newNode = newNode->next;
         if (newNode == 0){
            printf("NO MEMORY\n");
            exit(1);
         }
      }
      
      newNode->next = 0;
      newNode->val = i; //i is the line number
      firstNode->last = newNode;
      sizeofEachPartition[c] = sizeofEachPartition[c] + 1;
      i++;
   }
   printf("FINISHED READING PARTITION FILE\n");
   fclose(partFile);
   
   //Contains partitioned matrix Data
   partitionedMatrixData = malloc(partitionCount * sizeof(struct row));
   for (i=0; i<partitionCount; i++) {
      partitionedMatrixData[i].rowary = malloc(sizeofEachPartition[i] * sizeof(rowData));
      partitionedMatrixData[i].rcount = sizeofEachPartition[i];
   }
   free(sizeofEachPartition);

   printf("PARTITION MATRIX\n");
   //Partition the Matrix. Going through each partition
   for (i=0;i<partitionCount;i++){
      struct pNode *newNode = &partitionArray[i];
      //newNode->val contains the row number (node id)
      int rc = 0;
      while (newNode != NULL) {
         partitionedMatrixData[i].rowary[rc].values = malloc(matrixdata.rowary[newNode->val].vcount * sizeof(double));
         partitionedMatrixData[i].rowary[rc].col = malloc(matrixdata.rowary[newNode->val].vcount * sizeof(long int));
         for (c=0; c<matrixdata.rowary[newNode->val].vcount; c++){
            partitionedMatrixData[i].rowary[rc].values[c] = matrixdata.rowary[newNode->val].values[c]; 
            partitionedMatrixData[i].rowary[rc].col[c]    = matrixdata.rowary[newNode->val].col[c];
         }
         partitionedMatrixData[i].rowary[rc].vcount = matrixdata.rowary[newNode->val].vcount;
         partitionedMatrixData[i].rowary[rc].rowId  = newNode->val;
         newNode = newNode->next;
         rc++;
      }
   }
   numberofRows = matrixdata.rcount;
   for (c=0; c < matrixdata.rcount; c++) {    
      free(matrixdata.rowary[c].col);
      free(matrixdata.rowary[c].values);
   }
   free(matrixdata.rowary);
   free(partitionArray);
   printf("MATRIX PARTITIONED\n");
   
   printf("INITIALIZE MULTIPLY ARRAY\n");
   //multiplyArray = (double *) malloc(numberofRows + (numberofRows * 50) * sizeof(double));
   multiplyArray = (double *) malloc(numberofRows * sizeof(double));
   for (c=0; c < numberofRows; c++) {
      multiplyArray[c] = 1/(double)numberofRows;
   }
   printf("MULTIPLY ARRAY CREATED\n");
   printf("CALCULATING NORMS\n");
   
   //totalSumAtEachPartition = (double *) malloc(partitionCount * sizeof(double));
   totalSum = 0;
   gettimeofday(&start, NULL);
   for(i=0; i<max_threads; i++) {
      int *arg = malloc(sizeof(*arg));
      *arg = i;
      pthread_create(&p_threads[i], &attr, compute, arg);
   }
   for (i=0; i<max_threads; i++) {
      pthread_join(p_threads[i], NULL);
   }
   gettimeofday(&end, NULL);
   //free(totalSumAtEachPartition);
   
   printf("normalizedValue = %f\n", norm);
   long runTime = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec);
   printf("TIME: %ld\n", runTime);

   FILE *fp;
   fp = fopen("pagerank.result", "w+");
   fprintf(fp,"time: %ld\n", runTime);
   fprintf(fp,"node_Id pagerank \n");
   for (c=0; c < numberofRows; c++) {
      fprintf(fp, "%d %.12f\n", c, multiplyArray[c]);
   }
   fclose(fp);
   
   for (i=0; i<partitionCount; i++) {
      for (c=0; c<partitionedMatrixData[i].rcount; c++) {
         free(partitionedMatrixData[i].rowary[c].col);
         free(partitionedMatrixData[i].rowary[c].values);
      }
      free(partitionedMatrixData[i].rowary);
   }
   free(partitionedMatrixData);
   free(multiplyArray);
}
示例#10
0
int uv_barrier_init(uv_barrier_t* barrier, unsigned int count) {
  return UV__ERR(pthread_barrier_init(barrier, NULL, count));
}
示例#11
0
文件: mdl.c 项目: N-BodyShop/mdl
int mdlInitialize(MDL *pmdl,char **argv,void (*fcnChild)(MDL))
{
    MDL mdl,tmdl;
    int i,nThreads,bThreads,bDiag;
    char *p,ach[256],achDiag[256];
    
    *pmdl = NULL;
    /*
     ** Do some low level argument parsing for number of threads, and
     ** diagnostic flag!
     */
    bDiag = 0;
    bThreads = 0;
    i = 1;
    while (argv[i]) {
		if (!strcmp(argv[i],"-sz") && !bThreads) {
			++i;
			if (argv[i]) {
				nThreads = atoi(argv[i]);
				bThreads = 1;
				}
			}
		if (!strcmp(argv[i],"+d") && !bDiag) {
			p = getenv("MDL_DIAGNOSTIC");
			if (!p) p = getenv("HOME");
			if (!p) sprintf(ach,"/tmp");
			else sprintf(ach,"%s",p);
			bDiag = 1;
			}
		++i;
		}
    if (!bThreads) {
		nThreads = pthread_procsetinfo(NULL,0);
		}
    mdl = malloc(sizeof(struct mdlContext));
    assert(mdl != NULL);
    mdl->pmdl = malloc(nThreads*sizeof(MDL));
    assert(mdl->pmdl != NULL);
    mdl->pmdl[0] = mdl;			/* that's me! */
    mdl->pt = (pthread_t *)malloc(nThreads*sizeof(pthread_t));
    assert(mdl->pt != NULL);
    /*
     ** Initialize caching barrier.
     */
    pthread_barrier_init(&mdl->bar,pthread_barrierattr_default,nThreads);
    *pmdl = mdl;
    if (nThreads > 1) {
		for (i=1;i<nThreads;++i) {
			/*
			 ** Allocate the children mdl data structures.
			 */
			tmdl = malloc(sizeof(struct mdlContext));
			assert(tmdl != NULL);
			mdl->pmdl[i] = tmdl;
			tmdl->pt = NULL;
			}
		for (i=0;i<nThreads;++i) {
			/*
			 ** Set up all the mdl data structures.
			 */
			tmdl = mdl->pmdl[i];
            BasicInit(tmdl);
			tmdl->pmdl = mdl->pmdl;
			tmdl->idSelf = i;
			tmdl->bDiag = bDiag;
			tmdl->nThreads = nThreads;
			if (tmdl->bDiag) {
				sprintf(achDiag,"%s.%d",ach,tmdl->idSelf);
				tmdl->fpDiag = fopen(achDiag,"w");
				assert(tmdl->fpDiag != NULL);
				}
			}
		for (i=1;i<nThreads;++i) {
			/*
			 ** Start all the children.
			 */
			pthread_create(&mdl->pt[i],pthread_attr_default,fcnChild,
						   mdl->pmdl[i]);
			}
		return(nThreads);
		}
    else {
		/*
		 ** A unik!
		 */
        BasicInit(mdl);
		mdl->bDiag = bDiag;
		mdl->nThreads = 1;
		mdl->idSelf = 0;
		if (mdl->bDiag) {
			sprintf(achDiag,"%s.%d",ach,mdl->idSelf);
			mdl->fpDiag = fopen(achDiag,"w");
			assert(mdl->fpDiag != NULL);
			}
		return(nThreads);
		}
    }
示例#12
0
int main(int argc, char *argv[])
{
	int node_id = 0;
	int arrival_lambda = 10;
	int thread_cpu_map[N_THREADS];
	int i,j,k;
	int n_threads;
	int n_left;
	int n_right;
	int next_index_left = 3;
	int next_index_right = 7;
	float local_square = 0.0, remote_square = 0.0;


	/***************** make sure #args is correct and get the n_threads, n_left and n_right */
	if(argc < 4)
	{
		printf("Usage: ./test_numa_comb n_of_threads n_of_threads_on_node0 n_of_threads_on_node1\n");
		exit(-1);
	}
	n_threads = atoi(argv[1]);
	n_left = atoi(argv[2]);
	n_right = atoi(argv[3]);
	/******************* Set the thread_cpu_map according to the n_left and n_right */
	printf("n_threads: %d, n_left: %d, n_right: %d\n",n_threads,n_left,n_right);
	for(i = 0; i < n_left; i++)
	{
		thread_cpu_map[i] = next_index_left;
		next_index_left--;
	}
	for(i = n_left; i < n_threads; i++)
	{
		thread_cpu_map[i] = next_index_right;
		next_index_right--;
	}
	for(i = 0; i < n_threads; i++)
	{
		printf("Thread %d is on cpu %d\n",i,thread_cpu_map[i]);
	}



	thread_params para[n_threads]; //The parameters to pass to the threads

	//printf("The return value of numa_get_run_node_mask(void) is %d\n",numa_get_run_node_mask());
	//printf("The return value of numa_max_node(void) is %d\n",numa_max_node());
	//numa_tonode_memory((void *)spinlock_ptr,sizeof(pthread_spinlock_t),node_id); //This doesn't work

	//initilize the spinlock pointer and put it on a specific node
	pthread_spinlock_t *spinlock_ptr = numa_alloc_onnode(sizeof(pthread_spinlock_t),node_id);

	if(spinlock_ptr == NULL) //error handling of the allocating of a spinlock pointer on a specific node
	{
		printf("alloc of spinlock on a node failed.\n");
		exit(-1);
	}

	/* initialise  syncs */
	pthread_barrier_init(&fin_barrier, NULL, n_threads);
	pthread_spin_init(spinlock_ptr,0);
	int rc;
	//create the threads
	for(i = 0; i < n_threads; i++)
	{

		para[i].thread_id = i;
		para[i].arrival_lambda = arrival_lambda;
		para[i].spinlock_ptr = spinlock_ptr;
		CPU_ZERO(&cpuset[i]);
		CPU_SET(thread_cpu_map[i],&cpuset[i]);
		rc = pthread_create(&threads[i],NULL,work,(void*)&para[i]);
		E (rc);


	}
	start_work_flag = 1; 

	/* wait here */
	for(i = 0; i < n_threads; i++)
	    pthread_join(threads[i],NULL);


	pthread_barrier_destroy(&fin_barrier);

	/*
	for(i = 0; i < n_threads; i++)
	{
		printf("The time to get one lock for thread %d is : %.9f\n",i,time_in_cs[i]/num_access_each_thread[i]);
		printf("The number of lock accesses for thread %d is : %d\n",i,num_access_each_thread[i]);
	}
	*/

	qsort((void*)g_tss,(size_t)access_count,(size_t)sizeof(timestamp),cmp_timestamp);
	/*
	for (i = 0; i < access_count; i++)
		printf("%lu with id %d\n",g_tss[i].ts,g_tss[i].id);
	*/

	/* for (i = 0; i < access_count; i++)
	 * {
	 *     printf ("%lu %d\n", g_tss[i].ts, g_tss[i].id);
	 * } */

	/* */
	
	int cs_order[access_count/2];
	for(i = 0; i < access_count/2; i++)
	{
		cs_order[i] = g_tss[i*2].id;
		//printf("%d in cs\n",cs_order[i]);
	}
	int cs_matrix[n_threads][n_threads];
	uint64_t delay_matrix[n_threads][n_threads];
	float prob_matrix[n_threads][n_threads];
	float rate_matrix[n_threads][n_threads];

	// zero out all the matrices
	memset(&cs_matrix, '\0', n_threads*n_threads*sizeof(int));
	memset(&delay_matrix, '\0', n_threads*n_threads*sizeof(uint64_t));
	memset(&prob_matrix, '\0', n_threads*n_threads*sizeof(float));


	int local_count2 = 0, remote_count2 = 0;
	uint64_t diff;
	for(i = 0; i < n_threads; i++)
	    for(j = 0; j < n_threads; j++)
		for(k = 0; k < access_count/2 -1 ; k++)
		{
		    if(cs_order[k] == i && cs_order[k+1] == j)
		    {
			cs_matrix[i][j]++;
			diff = g_tss[2*k+2].ts - g_tss[2*k+1].ts; 
			delay_matrix[i][j] += diff;
			if(is_on_same_node(i, j, n_threads, n_left, n_right))
			{
			    dprintf("local_delay: %lu\n", diff);
			    local_square += sqr(diff);
			    local_count2++;
			}
			else
			{
			    dprintf("remote_delay: %lu\n", diff);
			    remote_square += sqr(diff);
			    remote_count2++;
			}
		    }
		}

	int num_access[n_threads];
	for(i = 0; i < access_count/2 -1; i++)
	    for(j = 0; j < n_threads; j++)
	    {
		if (cs_order[i] == j) num_access[j]++;
	    }

	for(i = 0; i < n_threads; i++)
		printf("num_access[%d]:%d\n",i,num_access[i]);

	for(i = 0; i < n_threads; i++)
		for(j = 0; j < n_threads ; j++)
		{
			prob_matrix[i][j] = (float)cs_matrix[i][j]/(float)num_access[i];
			rate_matrix[i][j] = 1.0/((delay_matrix[i][j]/(float)cs_matrix[i][j])/CPU_FREQ);
		}


	printf ("\n***************** PROBS *******************\n");
	printf ("Lock is on LP, [L, R] is [%d, %d]:\n", n_left - 1, n_right);
	// tl
	printf ("L -> L\n");
	print_mtx (n_threads, n_threads, prob_matrix,
			   0, 0, n_left, n_left, 0);
    // tr
	printf ("L -> R\n");
	print_mtx (n_threads, n_threads, prob_matrix,
			   n_left, 0, n_threads, n_left, 0);

	printf ("Lock is on RP, [L, R] is [%d, %d]:\n", n_left, n_right - 1);
	// br
	printf ("R -> R\n");
	print_mtx (n_threads, n_threads, prob_matrix,
			   n_left, n_left, n_threads, n_threads, 0);
	// bl
	printf ("R -> L\n");
	print_mtx (n_threads, n_threads, prob_matrix,
			   0, n_left, n_left, n_threads, 0);
	

	printf ("\n***************** RATES *******************\n");

	printf ("Lock is on LP, [L, R] is [%d, %d]:\n", n_left - 1, n_right);
	// tl
	printf ("L -> L\n");
	print_mtx (n_threads, n_threads, rate_matrix,
			   0, 0, n_left, n_left, 1);
    // tr
	printf ("L -> R\n");
	print_mtx (n_threads, n_threads, rate_matrix,
			   n_left, 0, n_threads, n_left, 1);

	printf ("Lock is on RP, [L, R] is [%d, %d]:\n", n_left, n_right - 1);
	// br
	printf ("R -> R\n");
	print_mtx (n_threads, n_threads, rate_matrix,
			   n_left, n_left, n_threads, n_threads, 1);
	// bl
	printf ("R -> \n");
	print_mtx (n_threads, n_threads, rate_matrix,
			   0, n_left, n_left, n_threads, 1);




	//print the intra-core and inter-core delay
	//thread 0 - n_left -1 are on the left core, n_left to n_threads are on the right core
	uint64_t local_delay = 0, remote_delay = 0;
	int local_count = 0, remote_count = 0;
	float local_prob = 0.0, remote_prob = 0.0;

	for(i = 0; i < n_threads; i++)
	    for(j = 0; j < n_threads; j++)
	    {
			if (j == i)
				continue;
			if(is_on_same_node(i, j, n_threads, n_left, n_right))
			{
				//printf("%d and %d on the same node\n",i,j);
				local_delay += delay_matrix[i][j];
				local_count += cs_matrix[i][j];
				local_prob += prob_matrix[j][i];
			}
			else
			{
				//printf("%d and %d not the same node\n",i,j);
				remote_delay += delay_matrix[i][j];
				remote_count += cs_matrix[i][j];
				remote_prob += prob_matrix[j][i];
			}
	    }


	float local = (float)local_delay/(local_count);
	float remote = (float)remote_delay/(remote_count);

	printf("\n\n**************************** Aggregates ***************************\n");
	printf("local delay: %f, remote_delay: %f, local_count: %d, remote_count: %d\n",(float)local_delay/(local_count),(float)remote_delay/(remote_count),local_count,remote_count);
	printf("local prob:%f, remote prob: %f\n",local_prob/n_threads, remote_prob/n_threads);
	printf("local delay variance:%f, remote delay variance: %f\n",local_square/local_count - local*local, remote_square/remote_count - remote*remote);
	printf("local count2: %d, remote_count2:%d\n",local_count2, remote_count2);
	pthread_spin_destroy(spinlock_ptr);
	numa_free((void *)spinlock_ptr,sizeof(pthread_spinlock_t));
	pthread_exit(NULL);
	return 0;
}
int main(int argc, char **argv)
{
  cpu_set_t dp;
  int retval[2];

  if (argc > 1)
    niter = atoi(argv[1]);

  signal(SIGALRM, sighand_alrm);
  
  ERRHAND(tmc_cpus_get_dataplane_cpus(&dp));  
  ERRHAND(cpu_snd = tmc_cpus_find_first_cpu(&dp));
  ERRHAND(cpu_rcv = tmc_cpus_find_last_cpu(&dp));
  
  ERRHAND_NZ(pthread_barrier_init(&computation_end, NULL, 2));

  for (cur_suite=0; cur_suite<niter; cur_suite++) {
    PRINT(fprintf(stderr, "[INFO] start test suite %d\n", cur_suite));
    /* --> init shared objects */
    ERRHAND_NN(ch = ch_sym_ref_sm_create(M, cpu_snd, cpu_rcv, NULL));
    /* set deadlock alarm */
    alarm(deadlock_timeout);

    /* start */
    ERRHAND(gettimeofday(&start, NULL));
    ERRHAND_NZ
      (pthread_create(&thread_producer, NULL, task_producer, (void *)cpu_snd));
    ERRHAND_NZ
      (pthread_create(&thread_consumer, NULL, task_consumer, (void *)cpu_rcv));
    /* wait end */
    ERRHAND_NZ(pthread_join(thread_producer, (void *)retval));
    ERRHAND_NZ(pthread_join(thread_consumer, (void *)(retval+1)));
    /* end */
    ERRHAND(gettimeofday(&end, NULL)); 

    timersub(&end, &start, &start);
    prepareStatistics(time_suite, start.tv_sec*1000+start.tv_usec/(double)1000);
    prepareStatistics(result_suite, retval[0] + retval[1]);
    PRINT(fprintf(stderr, "[INFO] end test suite %d: producer %d consumer %d\n",
		  cur_suite, retval[0], retval[1]));
    /* --> destroy shared object */
    ch_sym_ref_sm_destroy(&ch);
    deadlock_continue = 0;
  }

  calcStatistics(avg[0], sdev[0], result_suite, niter);
  calcStatistics(avg[1], sdev[1], time_suite, niter);  

  printf(printStatistics_format("return values", PRIu64)
	 printStatistics_format("elapsed time", "f")
	 printStatistics_format("Tcall-send", PRIu64)
	 printStatistics_format("Tcall-recv", PRIu64)
	 printStatistics_format("Tsend", PRIu64),
	 printStatistics_values(avg[0], sdev[0], result_suite),
	 printStatistics_values(avg[1], sdev[1], time_suite),
	 printStatistics_values(avg[2], sdev[2], call_send),
	 printStatistics_values(avg[3], sdev[3], call_recv),
	 printStatistics_values(avg[4], sdev[4], send)
	 );

  return result_suite[1];
}
示例#14
0
static int
do_test (void)
{
  char tmp[] = "/tmp/tst-signal1-XXXXXX";

  int fd = mkstemp (tmp);
  if (fd == -1)
    {
      puts ("mkstemp failed");
      exit (1);
    }

  unlink (tmp);

  int i;
  for (i = 0; i < 20; ++i)
    write (fd, "foobar xyzzy", 12);

  b = mmap (NULL, sizeof (pthread_barrier_t), PROT_READ | PROT_WRITE,
	    MAP_SHARED, fd, 0);
  if (b == MAP_FAILED)
    {
      puts ("mmap failed");
      exit (1);
    }

  pthread_barrierattr_t ba;
  if (pthread_barrierattr_init (&ba) != 0)
    {
      puts ("barrierattr_init failed");
      exit (1);
    }

  if (pthread_barrierattr_setpshared (&ba, PTHREAD_PROCESS_SHARED) != 0)
    {
      puts ("barrierattr_setpshared failed");
      exit (1);
    }

  if (pthread_barrier_init (b, &ba, 2) != 0)
    {
      puts ("barrier_init failed");
      exit (1);
    }

  if (pthread_barrierattr_destroy (&ba) != 0)
    {
      puts ("barrierattr_destroy failed");
      exit (1);
    }

  pid_t pid = fork ();
  if (pid == -1)
    {
      puts ("fork failed");
      exit (1);
    }

  if (pid == 0)
    receiver ();

  pthread_barrier_wait (b);

  /* Wait a bit more.  */
  struct timespec ts = { .tv_sec = 0, .tv_nsec = 10000000 };
  nanosleep (&ts, NULL);

  /* Send the signal.  */
  puts ("sending the signal now");
  kill (pid, SIGINT);

  /* Wait for the process to terminate.  */
  int status;
  if (TEMP_FAILURE_RETRY (waitpid (pid, &status, 0)) != pid)
    {
      puts ("wrong child reported terminated");
      exit (1);
    }

  if (!WIFSIGNALED (status))
    {
      puts ("child wasn't signalled");
      exit (1);
    }

  if (WTERMSIG (status) != SIGINT)
    {
      puts ("child not terminated with SIGINT");
      exit (1);
    }

  return 0;
}
示例#15
0
/**
 * @brief initializes a platform independent barrier for init synchro
 *
 * @param bar     pointer to the barrier memory area
 * @param attr    attributes for the barrier if any
 * @param count   number of threads
 *
 * @returns SMELT_SUCCESS or error value
 */
errval_t smlt_platform_barrier_init(smlt_platform_barrier_t *bar,
                                    smlt_platform_barrierattr_t *attr,
                                    uint32_t count)
{
    return pthread_barrier_init(bar, attr, count);
}
示例#16
0
文件: Mavlink.c 项目: limoges/drone
int MavlinkInit(MavlinkStruct *Mavlink, AttitudeData *AttitudeDesire, AttitudeData *AttitudeMesure, char *TargetIP) {
	pthread_attr_t		attr;
	struct sched_param	param;
	int					minprio, maxprio;
	int retval = 0;

	Mavlink->AttitudeDesire = AttitudeDesire;
	Mavlink->AttitudeMesure = AttitudeMesure;

	strcpy(Mavlink->target_ip, TargetIP);
	Mavlink->sock 		= socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	memset((void *) &(Mavlink->locAddr), 0, sizeof(struct sockaddr_in));
	Mavlink->locAddr.sin_family 	 = AF_INET;
	Mavlink->locAddr.sin_addr.s_addr = INADDR_ANY;
	Mavlink->locAddr.sin_port 		 = htons(14551);

	/* Bind the socket to port 14551 - necessary to receive packets from qgroundcontrol */ 
	retval = bind(Mavlink->sock,(struct sockaddr *)&(Mavlink->locAddr), sizeof(struct sockaddr));
	if (retval == -1) {
		printf("%s : erreur bind échoué", __FUNCTION__);
		close(Mavlink->sock);
		return retval;
	} 

	/* Attempt to make it non blocking */
	if ((retval = fcntl(Mavlink->sock, F_SETFL, fcntl(Mavlink->sock, F_GETFL) | O_ASYNC | O_NONBLOCK)) < 0) {
		printf("%s : erreur ouverture non-bloquante", __FUNCTION__);
		close(Mavlink->sock);
		return retval;
	}

	memset(&Mavlink->gcAddr, 0, sizeof(struct sockaddr_in));
	Mavlink->gcAddr.sin_family 		= AF_INET;
	Mavlink->gcAddr.sin_addr.s_addr = inet_addr(Mavlink->target_ip);
	Mavlink->gcAddr.sin_port 		= htons(14550);

	pthread_attr_init(&attr);
	pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
	pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
	minprio = sched_get_priority_min(POLICY);
	maxprio = sched_get_priority_max(POLICY);
	pthread_attr_setschedpolicy(&attr, POLICY);
	param.sched_priority = minprio + (maxprio - minprio)/4;
	pthread_attr_setstacksize(&attr, THREADSTACK);
	pthread_attr_setschedparam(&attr, &param);

	printf("Creating Mavlink thread\n");
	pthread_barrier_init(&MavlinkStartBarrier, NULL, 3);

	sem_init(&MavlinkReceiveTimerSem, 0, 0);
	sem_init(&MavlinkStatusTimerSem, 0, 0);

	retval = pthread_create(&Mavlink->MavlinkReceiveTask, &attr, MavlinkReceiveTask, Mavlink);
	if (retval) {
		printf("pthread_create : Impossible de créer le thread Mavlink_reception_thread\n");
		return retval;
	}

	retval = pthread_create(&Mavlink->MavlinkStatusTask, &attr, MavlinkStatusTask, Mavlink);
	if (retval) {
		printf("pthread_create : Impossible de créer le thread MavlinkStatusTask\n");
		return retval;
	}

	pthread_attr_destroy(&attr);

	return retval;
}
示例#17
0
int main(int argc, char **argv)
{
    char name[100];
    num_threads = sysconf(_SC_NPROCESSORS_ONLN);
    errval_t err;

    err = smlt_init(num_threads, true);
    if (smlt_err_is_fail(err)) {
	    printf("FAILED TO INITIALIZE !\n");
	    return 1;
    }

    for (int i = 4; i < num_threads+1; i++) {

        pthread_barrier_init(&bar, NULL, i);
        printf("Running %d cores\n", i);

        active_threads = i;
        uint32_t* cores = placement(i, false);
        for (int j = 0; j < i; j++) {
            printf("Cores[%d]=%d\n",j,cores[j]);
        }

        active_cores = cores;

        printf("Generating model\n");
        struct smlt_generated_model* model = NULL;
        err = smlt_generate_model(cores, i, NULL, &model);
        if (smlt_err_is_fail(err)) {
            exit(0);
        }

        printf("Generating topology\n");
        struct smlt_topology *topo = NULL;
        sprintf(name, "adaptivetree_rr%d",i);
        smlt_topology_create(model, name, &topo);
        active_topo = topo;

        printf("Generating context\n");
        err = smlt_context_create(topo, &context);
        if (smlt_err_is_fail(err)) {
            printf("FAILED TO INITIALIZE CONTEXT !\n");
            return 1;
        }
       
        printf("----------------------------------------\n");
        printf("Executing Barrier with %d cores rr\n", i);
        printf("----------------------------------------\n");
        
        struct smlt_node *node;
        for (uint64_t j = 0; j < i; j++) {
            node = smlt_get_node_by_id(cores[j]);
            err = smlt_node_start(node, barrier, (void*) j);
            if (smlt_err_is_fail(err)) {
                printf("Staring node failed \n");
            }   
        }

        for (int j=0; j < i; j++) {
            node = smlt_get_node_by_id(cores[j]);
            smlt_node_join(node);
        }
    }

    for (int i = 4; i < num_threads+1; i++) {

        pthread_barrier_init(&bar, NULL, i);

        active_threads = i;
        uint32_t* cores = placement(i, true);
        for (int j = 0; j < i; j++) {
            printf("Cores[%d]=%d\n",j,cores[j]);
        }

        active_cores = cores;

        struct smlt_generated_model* model = NULL;
        err = smlt_generate_model(cores, i, NULL, &model);
        if (smlt_err_is_fail(err)) {
            exit(0);
        }

        struct smlt_topology *topo = NULL;
        sprintf(name, "adaptivetree_fill%d",i);
        smlt_topology_create(model, name, &topo);
        active_topo = topo;

        err = smlt_context_create(topo, &context);
        if (smlt_err_is_fail(err)) {
            printf("FAILED TO INITIALIZE CONTEXT !\n");
            return 1;
        }
       
        printf("----------------------------------------\n");
        printf("Executing Barrier with %d cores fill\n", i);
        printf("----------------------------------------\n");
        
        struct smlt_node *node;
        for (uint64_t j = 0; j < i; j++) {
            node = smlt_get_node_by_id(cores[j]);
            err = smlt_node_start(node, barrier, (void*) j);
            if (smlt_err_is_fail(err)) {
                printf("Staring node failed \n");
            }   
        }

        for (int j=0; j < i; j++) {
            node = smlt_get_node_by_id(cores[j]);
            smlt_node_join(node);
        }
    }

}
示例#18
0
/* The main test function. */
int main( int argc, char *argv[] )
{
	int ret = 0;
	pthread_t child;
	pthread_attr_t ta;
	pthread_barrier_t bar;

	struct sched_param sp;

	/* Initialize output routine */
	output_init();

	ret = pthread_barrier_init( &bar, NULL, 2 );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to init barrier" );
	}

	/* Create the attribute object with a known scheduling policy */
	ret = pthread_attr_init( &ta );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to initialize thread attribute" );
	}

	ret = pthread_attr_setinheritsched( &ta, PTHREAD_EXPLICIT_SCHED );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to set inherit sched" );
	}

	sp.sched_priority = sched_get_priority_min( SCHED_RR );

	if ( sp.sched_priority == -1 )
	{
		UNRESOLVED( errno, "Failed to get min priority" );
	}

	ret = pthread_attr_setschedparam( &ta, &sp );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to set attribute param" );
	}

	ret = pthread_attr_setschedpolicy( &ta, SCHED_RR );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to set attribute policy" );
	}

	/* Create the thread with this attribute */
	ret = pthread_create( &child, &ta, threaded, &bar );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "thread creation failed (you may need more priviledges)" );
	}

	/* Wait while the thread checks its policy
	  (we only check what is reported, not the real behavior) 
	 */
	check_param( child, SCHED_RR, sched_get_priority_min( SCHED_RR ) );


	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}

	/* Change the threads policy */
	sp.sched_priority = sched_get_priority_min( SCHED_FIFO );

	if ( sp.sched_priority == -1 )
	{
		UNRESOLVED( errno, "Failed to get min priority" );
	}

	ret = pthread_setschedparam( child, SCHED_FIFO, &sp );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to change running thread's policy" );
	}

	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}

	/* Wait while the thread checks its policy
	  (we only check what is reported, not the real behavior) 
	 */
	check_param( child, SCHED_FIFO, sched_get_priority_min( SCHED_FIFO ) );

	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}

	/* Change the thread priority */
	sp.sched_priority = sched_get_priority_max( SCHED_FIFO );

	if ( sp.sched_priority == -1 )
	{
		UNRESOLVED( errno, "Failed to get max priority" );
	}

	ret = pthread_setschedprio( child, sp.sched_priority );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to raise thread's priority" );
	}

	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}

	/* The thread checks its priority
	  (we only check what is reported, not the real behavior) 
	 */
	check_param( child, SCHED_FIFO, sched_get_priority_max( SCHED_FIFO ) );

	ret = pthread_barrier_wait( &bar );

	if ( ( ret != 0 ) && ( ret != PTHREAD_BARRIER_SERIAL_THREAD ) )
	{
		UNRESOLVED( ret, "barrier wait failed" );
	}

	ret = pthread_join( child, NULL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to join the thread" );
	}

	PASSED;
}
示例#19
0
static int
do_test (void)
{
  int status = 0;

  if (pthread_barrier_init (&b, NULL, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  pthread_t th;
  if (pthread_create (&th, NULL, tf, NULL) != 0)
    {
      puts ("1st create failed");
      return 1;
    }
  int e = pthread_barrier_wait (&b);
  if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("1st barrier_wait failed");
      return 1;
    }
  if (pthread_mutex_lock (&m) != 0)
    {
      puts ("1st mutex_lock failed");
      return 1;
    }
  if (pthread_cond_signal (&c) != 0)
    {
      puts ("1st cond_signal failed");
      return 1;
    }
  if (pthread_cancel (th) != 0)
    {
      puts ("cancel failed");
      return 1;
    }
  if (pthread_mutex_unlock (&m) != 0)
    {
      puts ("1st mutex_unlock failed");
      return 1;
    }
  void *res;
  if (pthread_join (th, &res) != 0)
    {
      puts ("1st join failed");
      return 1;
    }
  if (res != PTHREAD_CANCELED)
    {
      puts ("first thread not canceled");
      status = 1;
    }

#ifndef OPAQUE_STRUCTS
  printf ("cond = { %d, %x, %lld, %lld, %lld, %p, %u, %u }\n",
	  c.__data.__lock, c.__data.__futex, c.__data.__total_seq,
	  c.__data.__wakeup_seq, c.__data.__woken_seq, c.__data.__mutex,
	  c.__data.__nwaiters, c.__data.__broadcast_seq);
#endif

  if (pthread_create (&th, NULL, tf, (void *) 1l) != 0)
    {
      puts ("2nd create failed");
      return 1;
    }
  e = pthread_barrier_wait (&b);
  if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("2nd barrier_wait failed");
      return 1;
    }
  if (pthread_mutex_lock (&m) != 0)
    {
      puts ("2nd mutex_lock failed");
      return 1;
    }
  if (pthread_cond_signal (&c) != 0)
    {
      puts ("2nd cond_signal failed");
      return 1;
    }
  if (pthread_mutex_unlock (&m) != 0)
    {
      puts ("2nd mutex_unlock failed");
      return 1;
    }
  if (pthread_join (th, &res) != 0)
    {
      puts ("2nd join failed");
      return 1;
    }
  if (res != NULL)
    {
      puts ("2nd thread canceled");
      status = 1;
    }

#ifndef OPAQUE_STRUCTS
  printf ("cond = { %d, %x, %lld, %lld, %lld, %p, %u, %u }\n",
	  c.__data.__lock, c.__data.__futex, c.__data.__total_seq,
	  c.__data.__wakeup_seq, c.__data.__woken_seq, c.__data.__mutex,
	  c.__data.__nwaiters, c.__data.__broadcast_seq);
#endif

  return status;
}
示例#20
0
static int
do_test (void)
{
  pthread_mutexattr_t a;
  if (pthread_mutexattr_init (&a) != 0)
    {
      puts ("mutexattr_init failed");
      return 1;
    }

  if (pthread_mutexattr_setrobust (&a, PTHREAD_MUTEX_ROBUST) != 0)
    {
      puts ("mutexattr_setrobust failed");
      return 1;
    }

#ifdef ENABLE_PI
  if (pthread_mutexattr_setprotocol (&a, PTHREAD_PRIO_INHERIT) != 0)
    {
      puts ("pthread_mutexattr_setprotocol failed");
      return 1;
    }
#endif

  int e;
  e = pthread_mutex_init (&m, &a);
  if (e != 0)
    {
#ifdef ENABLE_PI
      if (e == ENOTSUP)
	{
	  puts ("PI robust mutexes not supported");
	  return 0;
	}
#endif
      puts ("mutex_init failed");
      return 1;
    }

  if (pthread_mutexattr_destroy (&a) != 0)
    {
      puts ("mutexattr_destroy failed");
      return 1;
    }

  if (pthread_barrier_init (&b, NULL, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

#define N 5
  pthread_t th[N];
  for (long int n = 0; n < N; ++n)
    {
      if (pthread_create (&th[n], NULL, tf, (void *) n) != 0)
	{
	  printf ("pthread_create loop %ld failed\n", n + 1);
	  return 1;
	}

      e = pthread_barrier_wait (&b);
      if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
	{
	  printf ("parent: barrier_wait failed in round %ld\n", n + 1);
	  return 1;
	}
    }

  if (pthread_mutex_lock (&m) != 0)
    {
      puts ("parent: mutex_lock failed");
      return 1;
    }

  if (pthread_mutex_unlock (&m) != 0)
    {
      puts ("parent: mutex_unlock failed");
      return 1;
    }

  if (pthread_cond_broadcast (&c) != 0)
    {
      puts ("cond_broadcast failed");
      return 1;
    }

  for (int n = 0; n < N; ++n)
    {
      void *res;
      if (pthread_join (th[n], &res) != 0)
	{
	  printf ("join round %d failed\n", n + 1);
	  return 1;
	}
      if (res != PTHREAD_CANCELED)
	{
	  printf ("thread %d not canceled\n", n + 1);
	  return 1;
	}
    }

  e = pthread_mutex_lock (&m);
  if (e == 0)
    {
      puts ("parent: 2nd mutex_lock succeeded");
      return 1;
    }
  if (e != EOWNERDEAD)
    {
      puts ("parent: mutex_lock did not return EOWNERDEAD");
      return 1;
    }

  if (pthread_mutex_unlock (&m) != 0)
    {
      puts ("parent: 2nd mutex_unlock failed");
      return 1;
    }

  if (pthread_mutex_destroy (&m) != 0)
    {
      puts ("mutex_destroy failed");
      return 1;
    }

  return 0;
}
示例#21
0
文件: multithread6.c 项目: Aconex/pcp
int
main(int argc, char **argv)
{
    pthread_t	tid1;
    pthread_t	tid2;
    pthread_t	tid3;
    int		sts;
    char	*msg;
    int		errflag = 0;
    int		c;
    int		i;

    __pmSetProgname(argv[0]);

    while ((c = getopt(argc, argv, "D:")) != EOF) {
	switch (c) {

	case 'D':	/* debug flag */
	    sts = __pmParseDebug(optarg);
	    if (sts < 0) {
		fprintf(stderr, "%s: unrecognized debug flag specification (%s)\n",
		    pmProgname, optarg);
		errflag++;
	    }
	    else
		pmDebug |= sts;
	    break;

	case '?':
	default:
	    errflag++;
	    break;
	}
    }

    if (errflag || optind == argc || argc-optind > 3) {
	fprintf(stderr, "Usage: %s [-D...] host1 [host2 [host3]]\n", pmProgname);
	exit(1);
    }

    ctx1 = pmNewContext(PM_CONTEXT_HOST, argv[optind]);
    if (ctx1 < 0) {
	printf("Error: pmNewContext(%s) -> %s\n", argv[optind], pmErrStr(ctx1));
	exit(1);
    }
    optind++;

    if (optind < argc) {
	ctx2 = pmNewContext(PM_CONTEXT_HOST, argv[optind]);
	if (ctx2 < 0) {
	    printf("Error: pmNewContext(%s) -> %s\n", argv[optind], pmErrStr(ctx2));
	    exit(1);
	}
	optind++;
    }
    else
	ctx2 = ctx1;

    if (optind < argc) {
	ctx3 = pmNewContext(PM_CONTEXT_HOST, argv[optind]);
	if (ctx3 < 0) {
	    printf("Error: pmNewContext(%s) -> %s\n", argv[optind], pmErrStr(ctx2));
	    exit(1);
	}
	optind++;
    }
    else
	ctx3 = ctx2;

    sts = pmLookupName(NMETRIC, namelist, pmidlist);
    if (sts != NMETRIC) {
	printf("Error: pmLookupName -> %s\n", pmErrStr(sts));
	for (i = 0; i < NMETRIC; i++) {
	    printf("    %s -> %s\n", namelist[i], pmIDStr(pmidlist[i]));
	}
	exit(1);
    }

    for (i = 0; i < NMETRIC; i++) {
	if ((sts = pmLookupDesc(pmidlist[i], &desclist[i])) < 0) {
	    printf("Error: pmLookupDesc(%s) -> %s\n", namelist[i], pmErrStr(sts));
	    exit(1);
	}
    }

    sts = pthread_barrier_init(&barrier, NULL, 3);
    if (sts != 0) {
	printf("pthread_barrier_init: sts=%d\n", sts);
	exit(1);
    }

    sts = pthread_create(&tid1, NULL, func1, NULL);
    if (sts != 0) {
	printf("thread_create: tid1: sts=%d\n", sts);
	exit(1);
    }
    sts = pthread_create(&tid2, NULL, func2, NULL);
    if (sts != 0) {
	printf("thread_create: tid2: sts=%d\n", sts);
	exit(1);
    }
    sts = pthread_create(&tid3, NULL, func3, NULL);
    if (sts != 0) {
	printf("thread_create: tid3: sts=%d\n", sts);
	exit(1);
    }

    pthread_join(tid1, (void *)&msg);
    if (msg != NULL) printf("tid1: %s\n", msg);
    pthread_join(tid2, (void *)&msg); 
    if (msg != NULL) printf("tid2: %s\n", msg);
    pthread_join(tid3, (void *)&msg); 
    if (msg != NULL) printf("tid3: %s\n", msg);

    exit(0);
}
示例#22
0
/* Sets up and runs the threads
*/
void relaxationThreaded(float** inArray,
						float** outArray,
						int arraySize,
						float precision,
						int numThreads)
{
	if (numThreads > 0)
	{
		// Calculate granularity
		int currPos = 0;
		// plus 2 because we want to overlap and edges are
		// kept constant by the functions.
		int threadChunk = (arraySize / numThreads) + 2;

		// To store the data for the thread function
		LoopData	loopDataArray[numThreads];
		pthread_t 	threads[numThreads];

		// All threads must reach the barrier before we continue
		pthread_barrier_t theBarrier;
		pthread_barrier_init(&theBarrier, NULL, numThreads);

		// Shared counter so processes know when they're finished
		int finishedThreads = 0;

		// Lock for the counter
		pthread_mutex_t theLock;
		pthread_mutex_init(&theLock, NULL);

		// Loop and create/start threads
		int i;
		for ( i = 0; i < numThreads; i++)
		{
			// The last chunk is a bit of a special case
			if ( i == (numThreads - 1) )
			{
				int columnsRemaining 		= (arraySize - currPos);
				loopDataArray[i].arrayX 	= columnsRemaining;
				threadChunk 				= columnsRemaining;
			}
			else // It shouldn't be possible for any chunk but the last to go
			{   //  OOB, so keep that assumption (maybe bad practice, but
				//  protections higher up should hide it)
				loopDataArray[i].arrayX 	= threadChunk;
			}

			loopDataArray[i].inArray 		= &inArray[currPos];
			loopDataArray[i].outArray		= &outArray[currPos];

			loopDataArray[i].arrayY 		= arraySize;
			loopDataArray[i].precision 		= precision;
			loopDataArray[i].barrier		= &theBarrier;
			loopDataArray[i].numThreads		= numThreads;
			loopDataArray[i].finishedThreads= &finishedThreads;
			loopDataArray[i].finLock		= &theLock;

			if (__VERBOSE)
			{
				printf("Starting thread %d.\n", i);
			}

			pthread_create(&threads[i], NULL,
							threadLoop, (void*)&loopDataArray[i]);

			currPos += threadChunk - 2;

		}

		// join will block if the thread is going, otherwise doesn't block.
		for( i = 0; i < numThreads; i++)
		{
			pthread_join(threads[i], NULL);
		}

		// Cleanup
		pthread_barrier_destroy(&theBarrier);
		pthread_mutex_destroy(&theLock);
	}
	else
	{
		//== Serial Computation ==
		LoopData data;
		int finishedThreads = 0;

		data.inArray 	= inArray;
		data.outArray 	= outArray;
		data.arrayX 	= arraySize;
		data.arrayY		= arraySize;
		data.precision 	= precision;
		data.barrier 	= NULL;
		data.finLock	= NULL;
		data.numThreads = 1;
		data.finishedThreads = &finishedThreads;

		threadLoop((void*)&data);
	}
}
示例#23
0
static unsigned long long int
tsdiff (const struct timespec *before, const struct timespec *after)
{
  struct timespec diff = { .tv_sec = after->tv_sec - before->tv_sec,
			   .tv_nsec = after->tv_nsec - before->tv_nsec };
  while (diff.tv_nsec < 0)
    {
      --diff.tv_sec;
      diff.tv_nsec += 1000000000;
    }
  return diff.tv_sec * 1000000000ULL + diff.tv_nsec;
}

static unsigned long long int
test_nanosleep (clockid_t clock, const char *which,
		const struct timespec *before, int *bad)
{
  const struct timespec sleeptime = { .tv_nsec = 100000000 };
  int e = clock_nanosleep (clock, 0, &sleeptime, NULL);
  if (e == EINVAL || e == ENOTSUP || e == ENOSYS)
    {
      printf ("clock_nanosleep not supported for %s CPU clock: %s\n",
	      which, strerror (e));
      return 0;
    }
  if (e != 0)
    {
      printf ("clock_nanosleep on %s CPU clock: %s\n", which, strerror (e));
      *bad = 1;
      return 0;
    }

  struct timespec after;
  if (clock_gettime (clock, &after) < 0)
    {
      printf ("clock_gettime on %s CPU clock %lx => %s\n",
	      which, (unsigned long int) clock, strerror (errno));
      *bad = 1;
      return 0;
    }

  unsigned long long int diff = tsdiff (before, &after);
  if (diff < sleeptime.tv_nsec || diff > sleeptime.tv_nsec * 2)
    {
      printf ("clock_nanosleep on %s slept %llu (outside reasonable range)\n",
	      which, diff);
      *bad = 1;
      return diff;
    }

  struct timespec sleeptimeabs = sleeptime;
  sleeptimeabs.tv_sec += after.tv_sec;
  sleeptimeabs.tv_nsec += after.tv_nsec;
  while (sleeptimeabs.tv_nsec >= 1000000000)
    {
      ++sleeptimeabs.tv_sec;
      sleeptimeabs.tv_nsec -= 1000000000;
    }
  e = clock_nanosleep (clock, TIMER_ABSTIME, &sleeptimeabs, NULL);
  if (e != 0)
    {
      printf ("absolute clock_nanosleep on %s CPU clock: %s\n",
	      which, strerror (e));
      *bad = 1;
      return diff;
    }

  struct timespec afterabs;
  if (clock_gettime (clock, &afterabs) < 0)
    {
      printf ("clock_gettime on %s CPU clock %lx => %s\n",
	      which, (unsigned long int) clock, strerror (errno));
      *bad = 1;
      return diff;
    }

  unsigned long long int sleepdiff = tsdiff (&sleeptimeabs, &afterabs);
  if (sleepdiff > sleeptime.tv_nsec)
    {
      printf ("\
absolute clock_nanosleep on %s %llu past target (outside reasonable range)\n",
	      which, sleepdiff);
      *bad = 1;
    }

  unsigned long long int diffabs = tsdiff (&after, &afterabs);
  if (diffabs < sleeptime.tv_nsec || diffabs > sleeptime.tv_nsec * 2)
    {
      printf ("\
absolute clock_nanosleep on %s slept %llu (outside reasonable range)\n",
	      which, diffabs);
      *bad = 1;
    }

  return diff + diffabs;
}



static int
do_test (void)
{
  int result = 0;
  clockid_t process_clock, th_clock, my_thread_clock;
  int e;
  pthread_t th;

  e = clock_getcpuclockid (0, &process_clock);
  if (e != 0)
    {
      printf ("clock_getcpuclockid on self => %s\n", strerror (e));
      return 1;
    }

  e = pthread_getcpuclockid (pthread_self (), &my_thread_clock);
  if (e != 0)
    {
      printf ("pthread_getcpuclockid on self => %s\n", strerror (e));
      return 1;
    }

  /* This is a kludge.  This test fails if the semantics of thread and
     process clocks are wrong.  The old code using hp-timing without kernel
     support has bogus semantics if there are context switches.  We don't
     fail to report failure when the proper functionality is not available
     in the kernel.  It so happens that Linux kernels without correct CPU
     clock support also lack CPU timer support, so we use use that to guess
     that we are using the bogus code and not test it.  */
  timer_t t;
  if (timer_create (my_thread_clock, NULL, &t) != 0)
    {
      printf ("timer_create: %m\n");
      puts ("No support for CPU clocks with good semantics, skipping test");
      return 0;
    }
  timer_delete (t);


  pthread_barrier_init (&barrier, NULL, 2);

  e = pthread_create (&th, NULL, chew_cpu, NULL);
  if (e != 0)
    {
      printf ("pthread_create: %s\n", strerror (e));
      return 1;
    }

  e = pthread_getcpuclockid (th, &th_clock);
  if (e == ENOENT || e == ENOSYS || e == ENOTSUP)
    {
      puts ("pthread_getcpuclockid does not support other threads");
      return 1;
    }

  pthread_barrier_wait (&barrier);

  struct timespec res;
  if (clock_getres (th_clock, &res) < 0)
    {
      printf ("clock_getres on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      result = 1;
      return 1;
    }
  printf ("live thread clock %lx resolution %ju.%.9ju\n",
	  (unsigned long int) th_clock,
	  (uintmax_t) res.tv_sec, (uintmax_t) res.tv_nsec);

  struct timespec process_before, process_after;
  if (clock_gettime (process_clock, &process_before) < 0)
    {
      printf ("clock_gettime on process clock %lx => %s\n",
	      (unsigned long int) process_clock, strerror (errno));
      return 1;
    }

  struct timespec before, after;
  if (clock_gettime (th_clock, &before) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("live thread before sleep => %ju.%.9ju\n",
	  (uintmax_t) before.tv_sec, (uintmax_t) before.tv_nsec);

  struct timespec me_before, me_after;
  if (clock_gettime (my_thread_clock, &me_before) < 0)
    {
      printf ("clock_gettime on self thread clock %lx => %s\n",
	      (unsigned long int) my_thread_clock, strerror (errno));
      return 1;
    }
  printf ("self thread before sleep => %ju.%.9ju\n",
	  (uintmax_t) me_before.tv_sec, (uintmax_t) me_before.tv_nsec);

  struct timespec sleeptime = { .tv_nsec = 500000000 };
  if (nanosleep (&sleeptime, NULL) != 0)
    {
      perror ("nanosleep");
      return 1;
    }

  if (clock_gettime (th_clock, &after) < 0)
    {
      printf ("clock_gettime on live thread clock %lx => %s\n",
	      (unsigned long int) th_clock, strerror (errno));
      return 1;
    }
  printf ("live thread after sleep => %ju.%.9ju\n",
	  (uintmax_t) after.tv_sec, (uintmax_t) after.tv_nsec);

  if (clock_gettime (process_clock, &process_after) < 0)
    {
      printf ("clock_gettime on process clock %lx => %s\n",
	      (unsigned long int) process_clock, strerror (errno));
      return 1;
    }

  if (clock_gettime (my_thread_clock, &me_after) < 0)
    {
      printf ("clock_gettime on self thread clock %lx => %s\n",
	      (unsigned long int) my_thread_clock, strerror (errno));
      return 1;
    }
  printf ("self thread after sleep => %ju.%.9ju\n",
	  (uintmax_t) me_after.tv_sec, (uintmax_t) me_after.tv_nsec);

  unsigned long long int th_diff = tsdiff (&before, &after);
  unsigned long long int pdiff = tsdiff (&process_before, &process_after);
  unsigned long long int my_diff = tsdiff (&me_before, &me_after);

  if (th_diff < 100000000 || th_diff > 600000000)
    {
      printf ("live thread before - after %llu outside reasonable range\n",
	      th_diff);
      result = 1;
    }

  if (my_diff > 100000000)
    {
      printf ("self thread before - after %llu outside reasonable range\n",
	      my_diff);
      result = 1;
    }

  if (pdiff < th_diff)
    {
      printf ("process before - after %llu outside reasonable range (%llu)\n",
	      pdiff, th_diff);
      result = 1;
    }

  process_after.tv_nsec += test_nanosleep (th_clock, "live thread",
					   &after, &result);
  process_after.tv_nsec += test_nanosleep (process_clock, "process",
					   &process_after, &result);
  test_nanosleep (CLOCK_PROCESS_CPUTIME_ID,
		  "PROCESS_CPUTIME_ID", &process_after, &result);

  pthread_cancel (th);

  e = clock_nanosleep (CLOCK_THREAD_CPUTIME_ID, 0, &sleeptime, NULL);
  if (e != EINVAL)
    {
      printf ("clock_nanosleep CLOCK_THREAD_CPUTIME_ID: %s\n",
	      strerror (e));
      result = 1;
    }

  return result;
}
示例#24
0
int
do_test (void)
{
  if (pthread_barrier_init (&b, NULL, N + 1) != 0)
    {
      puts ("barrier_init failed");
      exit (1);
    }

  if (sem_init (&s, 0, 0) != 0)
    {
      puts ("sem_init failed");
      exit (1);
    }

  struct sigaction sa;
  sa.sa_handler = handler;
  sigemptyset (&sa.sa_mask);
  sa.sa_flags = 0;
  if (sigaction (THE_SIG, &sa, NULL) != 0)
    {
      puts ("sigaction failed");
      exit (1);
    }

  pthread_attr_t a;

  if (pthread_attr_init (&a) != 0)
    {
      puts ("attr_init failed");
      exit (1);
    }

  if (pthread_attr_setstacksize (&a, 1 * 1024 * 1024) != 0)
    {
      puts ("attr_setstacksize failed");
      return 1;
    }

  int i;
  for (i = 0; i < N; ++i)
    if (pthread_create (&th[i], &a, tf, cbs[i]) != 0)
      {
	puts ("pthread_create failed");
	exit (1);
      }

  if (pthread_attr_destroy (&a) != 0)
    {
      puts ("attr_destroy failed");
      exit (1);
    }

  pthread_barrier_wait (&b);

  sigset_t ss;
  sigemptyset (&ss);
  sigaddset (&ss, THE_SIG);
  if (pthread_sigmask (SIG_BLOCK, &ss, NULL) != 0)
    {
      puts ("pthread_sigmask failed");
      exit (1);
    }

  /* Start sending signals.  */
  for (i = 0; i < TOTAL_SIGS; ++i)
    {
      if (kill (getpid (), THE_SIG) != 0)
	{
	  puts ("kill failed");
	  exit (1);
	}

      if (TEMP_FAILURE_RETRY (sem_wait (&s)) != 0)
	{
	  puts ("sem_wait failed");
	  exit (1);
	}

      ++nsigs;
    }

  pthread_barrier_wait (&b);

  for (i = 0; i < N; ++i)
    if (pthread_join (th[i], NULL) != 0)
      {
	puts ("join failed");
	exit (1);
      }

  return 0;
}
示例#25
0
void barrier_test(void)
{
	pthread_t barrier_thread[CONFIG_EXAMPLES_KERNEL_SAMPLE_NBARRIER_THREADS];
	pthread_addr_t result;
	pthread_attr_t attr;
	pthread_barrierattr_t barrierattr;
	int status;
	int i;

	printf("barrier_test: Initializing barrier\n");

	status = pthread_barrierattr_init(&barrierattr);
	if (status != OK) {
		printf("barrier_test: pthread_barrierattr_init failed, status=%d\n", status);
	}

	status = pthread_barrier_init(&barrier, &barrierattr, CONFIG_EXAMPLES_KERNEL_SAMPLE_NBARRIER_THREADS);
	if (status != OK) {
		printf("barrier_test: pthread_barrierattr_init failed, status=%d\n", status);
	}

	/* Create the barrier */

	(void)pthread_barrierattr_init(&barrierattr);

	/* Start CONFIG_EXAMPLES_KERNEL_SAMPLE_NBARRIER_THREADS thread instances */

	status = pthread_attr_init(&attr);
	if (status != OK) {
		printf("barrier_test: pthread_attr_init failed, status=%d\n", status);
	}

	for (i = 0; i < CONFIG_EXAMPLES_KERNEL_SAMPLE_NBARRIER_THREADS; i++) {
		status = pthread_create(&barrier_thread[i], &attr, barrier_func, (pthread_addr_t)i);
		if (status != 0) {
			printf("barrier_test: Error in thread %d create, status=%d\n", i, status);
			printf("barrier_test: Test aborted with waiting threads\n");
			goto abort_test;
		} else {
			printf("barrier_test: Thread %d created\n", i);
		}
	}
	FFLUSH();

	/* Wait for all thread instances to complete */

	for (i = 0; i < CONFIG_EXAMPLES_KERNEL_SAMPLE_NBARRIER_THREADS; i++) {
		status = pthread_join(barrier_thread[i], &result);
		if (status != 0) {
			printf("barrier_test: Error in thread %d join, status=%d\n", i, status);
		} else {
			printf("barrier_test: Thread %d completed with result=%p\n", i, result);
		}
	}

	/* Destroy the barrier */

abort_test:
	status = pthread_barrier_destroy(&barrier);
	if (status != OK) {
		printf("barrier_test: pthread_barrier_destroy failed, status=%d\n", status);
	}

	status = pthread_barrierattr_destroy(&barrierattr);
	if (status != OK) {
		printf("barrier_test: pthread_barrierattr_destroy failed, status=%d\n", status);
	}
	FFLUSH();
}
示例#26
0
int
main(int argc, char *argv[])
{
	int ch, error, i;
	char *pagebuffer;
	uintmax_t total;
	size_t len;
	pid_t pid;

	numthreads = DEFAULTTHREADS;
	numseconds = DEFAULTSECONDS;
	while ((ch = getopt(argc, argv, "n:s:t")) != -1) {
		switch (ch) {
		case 'n':
			numthreads = atoi(optarg);
			break;

		case 's':
			numseconds = atoi(optarg);
			break;

		case 't':
			threaded = 1;
			break;

		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc != 3)
		usage();

	if (numthreads > MAXTHREADS)
		errx(-1, "%d exceeds max threads %d", numthreads,
		    MAXTHREADS);

	len = roundup(sizeof(struct state), getpagesize());
	pagebuffer = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_ANON, -1, 0);
	if (pagebuffer == MAP_FAILED)
		err(-1, "mmap");
	if (minherit(pagebuffer, len, INHERIT_SHARE) < 0)
		err(-1, "minherit");
	statep = (struct state *)pagebuffer;

	bzero(&statep->sin, sizeof(statep->sin));
	statep->sin.sin_len = sizeof(statep->sin);
	statep->sin.sin_family = AF_INET;
	statep->sin.sin_addr.s_addr = inet_addr(argv[0]);
	statep->sin.sin_port = htons(atoi(argv[1]));
	statep->path = argv[2];

	/*
	 * Do one test retrieve so we can report the error from it, if any.
	 */
	if (http_fetch(&statep->sin, statep->path, 0) < 0)
		exit(-1);

	if (threaded) {
		if (pthread_barrier_init(&statep->start_barrier, NULL,
		    numthreads) != 0)
			err(-1, "pthread_barrier_init");
	}

	for (i = 0; i < numthreads; i++) {
		statep->hwd[i].hwd_count = 0;
		if (threaded) {
			if (pthread_create(&statep->hwd[i].hwd_thread, NULL,
			    http_worker, &statep->hwd[i]) != 0)
				err(-1, "pthread_create");
		} else {
			curthread = i;
			pid = fork();
			if (pid < 0) {
				error = errno;
				killall();
				errno = error;
				err(-1, "fork");
			}
			if (pid == 0) {
				http_worker(&statep->hwd[i]);
				printf("Doh\n");
				exit(0);
			}
			statep->hwd[i].hwd_pid = pid;
		}
	}
	if (!threaded) {
		signal(SIGHUP, main_sighup);
		sleep(2);
		signal_barrier_wakeup();
	}
	sleep(numseconds);
	statep->run_done = 1;
	if (!threaded)
		sleep(2);
	for (i = 0; i < numthreads; i++) {
		if (threaded) {
			if (pthread_join(statep->hwd[i].hwd_thread, NULL)
			    != 0)
				err(-1, "pthread_join");
		} else {
			pid = waitpid(statep->hwd[i].hwd_pid, NULL, 0);
			if (pid == statep->hwd[i].hwd_pid)
				statep->hwd[i].hwd_pid = 0;
		}
	}
	if (!threaded)
		killall();
	total = 0;
	for (i = 0; i < numthreads; i++)
		total += statep->hwd[i].hwd_count;
	printf("%ju transfers/second\n", total / numseconds);
	total = 0;
	for (i = 0; i < numthreads; i++)
		total += statep->hwd[i].hwd_errorcount;
	printf("%ju errors/second\n", total / numseconds);
	return (0);
}
示例#27
0
int main()
{
	int cnt = 0;
	int rc;
	pthread_t child_thread;
	sig_rcvd = 0;
	
	printf("Initialize barrier with count = 2\n");
	if(pthread_barrier_init(&barrier, NULL, 2) != 0)
	{
		printf("main: Error at pthread_barrier_init()\n");
		return PTS_UNRESOLVED;
	}

	printf("main: create child thread\n");
	thread_state = NOT_CREATED_THREAD;
	if(pthread_create(&child_thread, NULL, fn_chld, NULL) != 0)
	{
		printf("main: Error at pthread_create()\n");
		return PTS_UNRESOLVED;
	}
	
	/* Expect the child to block*/
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2); 
	
	if(thread_state == EXITING_THREAD)
	{
		/* child thread did not block */
		printf("Test FAILED: child thread did not block on "
			"pthread_barrier_wait()\n");
		exit(PTS_FAIL);
	}
	else if(thread_state != ENTERED_THREAD)
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}

	printf("main: send SIGUSR1 to child thread\n");
	if(pthread_kill(child_thread, SIGUSR1) != 0)
	{
		printf("main: Error at pthread_kill()\n");
		exit(PTS_UNRESOLVED);
	}

	/* Expect the child to continue blocking */
	cnt = 0;
	do{
		sleep(1);
	}while (thread_state !=EXITING_THREAD && cnt++ < 2); 
	
	if(sig_rcvd != 1)
	{
		printf("child did not handle SIGUSR1\n");
		exit(PTS_UNRESOLVED);
	}
	
	if(thread_state == EXITING_THREAD)
	{
		/* child thread did not block */
		printf("Test FAILED: child thread should still block on "
			"pthread_barrier_wait() when interrupted by signal\n");
		exit(PTS_FAIL);
	}
	else if(thread_state != ENTERED_THREAD)
	{
		printf("Unexpected thread state: %d\n", thread_state);
		exit(PTS_UNRESOLVED);
	}
	printf("main: thread continued blocking after handling SIGUSR1\n");
	
	printf("main: call barrier wait\n");
	rc = pthread_barrier_wait(&barrier);
	
	if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
	{
		printf("Test FAILED: main: pthread_barrier_wait() got unexpected "
			"return code : %d\n" , rc);
		exit(PTS_FAIL);
	} 
	else if(rc == PTHREAD_BARRIER_SERIAL_THREAD)
		printf("main: get PTHREAD_BARRIER_SERIAL_THREAD\n");
	
	/* We expected the child returned from barrier wait */
	cnt = 0;	
	do{
		sleep(1);
	}while (thread_state != EXITING_THREAD && cnt++ < 3); 
	
	if(thread_state == ENTERED_THREAD)
	{
		printf("Test FAILED: child thread still blocked on "
			"barrier wait\n");
		return PTS_FAIL;
	}
	else if(thread_state != EXITING_THREAD)
	{
		printf("main: Unexpected thread state: %d\n", thread_state);
		return PTS_UNRESOLVED;
	}

	if(pthread_join(child_thread, NULL) != 0)
	{
		printf("main: Error at pthread_join()\n");
		exit(PTS_UNRESOLVED);
	}

	if(pthread_barrier_destroy(&barrier) != 0)
	{
		printf("Error at pthread_barrier_destroy()");
		return PTS_UNRESOLVED;
	}	

	printf("Test PASSED\n");
	return PTS_PASS;
}
int main (int argc, char *argv[])
{
	struct timeval startt, endt, result;
	int i, j, k, nt, t, n, c;

	result.tv_sec = 0;
	result.tv_usec= 0;

	/* Test Correctness */
	printf("Test for correctness:\n");

	read_file("test01.in");
	printf("Input array: \n");
	print_array(A, file_size);

	printf("Results for sequential algorithm:\n");
	init(file_size);
	seq_function(file_size, 1);

	printf("Results for openmp algorithm:\n");
	init(file_size);
	openmp_function(file_size, 1, 2);

	printf("Results for pthread algorithm:\n");
	init(file_size);
	par_function(file_size, 2);
	printf("suffix minima: \n");
	print_array(B, file_size);
	printf("preffix minima: \n");
	print_array(C, file_size);

	/* Generate a seed input */
	srand ( time(NULL) );
	for(k=0; k<NMAX; k++){
		A[k] = rand();
	}

	printf("OpenMP:\n");
	printf("|NSize|Iterations| Seq | Th01 | Th02 | Th04 | Th08 | Par16|\n");

	// for each input size
	for(c=0; c<NSIZE; c++){
		n=Ns[c];
		printf("| %d | %d |",n,TIMES);

		/* Run sequential algorithm */
		result.tv_usec=0;
		gettimeofday (&startt, NULL);
		for (t=0; t<TIMES; t++) {
			init(n);
			seq_function(n, 0);
		}
		gettimeofday (&endt, NULL);
		result.tv_usec = (endt.tv_sec*1000000+endt.tv_usec) - (startt.tv_sec*1000000+startt.tv_usec);
		printf(" %ld.%06ld | ", result.tv_usec/1000000, result.tv_usec%1000000);

		/* Run OpenMP algorithm */
		for(nt=1; nt<NUM_THREADS; nt=nt<<1){
			result.tv_sec=0; 
			result.tv_usec=0;
			gettimeofday (&startt, NULL);
			for (t=0; t<TIMES; t++) 
			{
				init(n);
				openmp_function(n, 0, nt);
			}
			gettimeofday (&endt, NULL);
			result.tv_usec += (endt.tv_sec*1000000+endt.tv_usec) - (startt.tv_sec*1000000+startt.tv_usec);
			printf(" %ld.%06ld | ", result.tv_usec/1000000, result.tv_usec%1000000);
		}
		printf("\n");
	}

	/* Initialize and set thread detached attribute */
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

	printf("Pthread:\n");
	printf("|NSize|Iterations| Seq | Th01 | Th02 | Th04 | Th08 | Par16|\n");

	// for each input size
	for(c=0; c<NSIZE; c++){
		n=Ns[c];
		printf("| %d | %d |",n,TIMES);

		/* Run sequential algorithm */
		result.tv_usec=0;
		gettimeofday (&startt, NULL);
		for (t=0; t<TIMES; t++) {
			init(n);
			seq_function(n, 0);
		}
		gettimeofday (&endt, NULL);
		result.tv_usec = (endt.tv_sec*1000000+endt.tv_usec) - (startt.tv_sec*1000000+startt.tv_usec);
		printf(" %ld.%06ld | ", result.tv_usec/1000000, result.tv_usec%1000000);

		/* Run pthread algorithm(s) */
		for(nt=1; nt<NUM_THREADS; nt=nt<<1){
			if(pthread_barrier_init(&barr, NULL, nt+1))
			{
				printf("Could not create a barrier\n");
				return -1;
			}
			if(pthread_barrier_init(&internal_barr, NULL, nt))
			{
				printf("Could not create a barrier\n");
				return -1;
			}

			result.tv_sec=0; 
			result.tv_usec=0;

			gettimeofday (&startt, NULL);
			for (t=0; t<TIMES; t++) 
			{
				init(n);
				par_function(n, nt);
				// pthread_barrier_wait(&barr);
			}
			gettimeofday (&endt, NULL);

			if (pthread_barrier_destroy(&barr)) {
				printf("Could not destroy the barrier\n");
				return -1;
			}
			if (pthread_barrier_destroy(&internal_barr)) {
				printf("Could not destroy the barrier\n");
				return -1;
			}
			result.tv_usec += (endt.tv_sec*1000000+endt.tv_usec) - (startt.tv_sec*1000000+startt.tv_usec);
			printf(" %ld.%06ld | ", result.tv_usec/1000000, result.tv_usec%1000000);
		}
		printf("\n");
	}
	pthread_exit(NULL);
}
示例#29
0
static int
do_test (int argc, char *argv[])
{
  char name[] = "/tmp/aio2.XXXXXX";
  int fd;
  struct aiocb *arr[1];
  struct aiocb cb;
  static const char buf[] = "Hello World\n";

  fd = mkstemp (name);
  if (fd == -1)
    {
      printf ("cannot open temp name: %m\n");
      return 1;
    }

  unlink (name);

  if (pthread_barrier_init (&b, NULL, 2) != 0)
    {
      puts ("barrier_init failed");
      return 1;
    }

  arr[0] = &cb;

  void *p;
  int sz = set_o_direct (fd);
  if (sz != -1)
    {
      int err = posix_memalign (&p, sz, sz);
      if (err)
	{
	  errno = err;
	  printf ("cannot allocate memory: %m\n");
	  return 1;
	}
      memcpy (p, buf, sizeof (buf) - 1);
      memset (p + sizeof (buf) - 1, ' ', sz - sizeof (buf) + 1);
      printf ("Using O_DIRECT with block size %d\n", sz);
    }
  else
    {
      p = (void *) buf;
      sz = sizeof (buf) - 1;
    }

  cb.aio_fildes = fd;
  cb.aio_lio_opcode = LIO_WRITE;
  cb.aio_reqprio = 0;
  cb.aio_buf = p;
  cb.aio_nbytes = sz;
  cb.aio_offset = 0;
  cb.aio_sigevent.sigev_notify = SIGEV_THREAD;
  cb.aio_sigevent.sigev_notify_function = thrfct;
  cb.aio_sigevent.sigev_notify_attributes = NULL;
  cb.aio_sigevent.sigev_value.sival_ptr = NULL;

  if (lio_listio (LIO_WAIT, arr, 1, NULL) < 0)
    {
      if (errno == ENOSYS)
	{
	  puts ("no aio support in this configuration");
	  return 0;
	}
      printf ("lio_listio failed: %m\n");
      return 1;
    }

  puts ("lio_listio returned");

  int e = pthread_barrier_wait (&b);
  if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
    {
      puts ("barrier_wait failed");
      return 1;
    }

  puts ("all OK");

  return 0;
}
示例#30
0
int main(int argc, char *argv[])
{
    int size = atoi(argv[1]); //length of one size of the N x N matrix
    int nfill = atoi(argv[2]); //number of positions to fill in the matrix
    int num_threads = atoi(argv[3]); //number of threads
    int *matrix = malloc(size * size * sizeof(int)); //matrix to hold the values
    int *mask = malloc(size * size * sizeof(int)); //matrix to mark the filled spots
    pos *working_list = malloc(nfill * sizeof(pos)); //list of filled, but not surrounded cells
    pos *min_cells = malloc(num_threads * sizeof(pos)); //holds the maximum value found in each thread

    /*INTIALIZIE DATA STRUCTURES*/
    //seed random number generation
    srand(time(NULL));

    //generate ramdom matrix
    int i;
    for(i = 0; i < size; i++)
    {
        int j;
        for(j = 0; j < size; j++)
        {
            //fill with a random number 1 to 100
            matrix[size * i + j] = (rand() % 100) + 1;
        }
    }

    //intialize mask
    for(i = 0; i < size; i++)
    {
        int j;
        for(j = 0; j < size; j++)
        {
            //fill with "unfilled" represented by zero
            mask[size * i + j] = 0;
        }
    }

    //initialize working list
    for(i = 0; i < nfill; i++)
    {
        working_list[i].value = INT_MAX;
        working_list[i].x = -1;
        working_list[i].y = -1;
    }

    //find the center most cell and fill it as the start
    working_list[0].x = round(size / 2) - 1;
    working_list[0].y = round(size / 2) - 1;
    working_list[0].value = matrix[size * working_list[i].y + working_list[i].x];
    mask[size * working_list[0].y + working_list[0].x] = 1;
    matrix[size * working_list[0].y + working_list[0].x] = -1;
    filled = 1;
    
    //initialize min_cells
    for(i = 0; i < num_threads; i++)
    {
        min_cells[i].value = INT_MAX;
        min_cells[i].x = -1;
        min_cells[i].y = -1;
    }

    //intialize barrier
    pthread_barrier_init(&barrier, NULL, num_threads);

    //create threads
    pthread_t *find_lowest_t[num_threads];
    for(i = 0; i < num_threads; i++)
    {
        find_lowest_t[i] = malloc(sizeof(pthread_t));
    }

    //initialize thread data
    t_data *args;
    args = malloc(num_threads * sizeof(t_data));
    for(i = 0; i < num_threads; i++)
    {
        args[i].thread_id = i;
        args[i].num_threads = num_threads;
        args[i].size = size;
        args[i].matrix = matrix;
        args[i].mask = mask;
        args[i].working_list = working_list;
        args[i].min_cells = min_cells;
        args[i].nfill = nfill;    
    }

    /*LAUNCH THE THREADS*/
    for(i = 0; i < num_threads; i++)
    {
        pthread_create(find_lowest_t[i], NULL, find_lowest, (void *) &args[i]);
    }

    //join with all the threads
    for(i = 0; i < num_threads; i++)
    {
        pthread_join(*find_lowest_t[i], NULL);
    }

    int m;
    for(m = 0; m < size; m++)
    {
        int n;
        for(n = 0; n < size; n++)
        {
            printf("%d ", mask[size * m + n]);
        }

        printf("\n");
    }

    printf("\n");
    
    return(0);
}