All pastes #930737 Raw Edit

pthread __thread test

public c v1 · immutable
·published 2008-03-06 20:23 UTC
rendered paste body
#include <check.h>#include <stdio.h>#include <stdlib.h>#include <pthread.h>#define threadtest(attribute, varname, procname) \  attribute int varname; \  void *procname(void *arg) { \    int v = (int)arg; \    varname = v; \    pthread_mutex_lock(&m); \    results[v] = varname; \    pthread_mutex_unlock(&m); \    return NULL; \  }pthread_mutex_t m;int results[2];threadtest(static, aglobal_static, threadproc_static);threadtest(__thread, aglobal__thread, threadproc__thread);START_TEST(test_static_with_pthreads){  int rc;  pthread_t tid1, tid2;  results[0] = 3;  results[1] = 4;  fail_if(pthread_mutex_init(&m, NULL) != 0);  fail_if(pthread_mutex_lock(&m) != 0);  fail_if(pthread_create(&tid1, NULL, threadproc_static, (void*)0) != 0);  fail_if(pthread_create(&tid2, NULL, threadproc_static, (void*)1) != 0);  fail_if(pthread_mutex_unlock(&m) != 0);  fail_if(pthread_join(tid1, NULL) != 0);  fail_if(pthread_join(tid2, NULL) != 0);  fail_if(results[0] != results[1]);  fail_if(pthread_mutex_destroy(&m) != 0);}END_TESTSTART_TEST(test_thread_with_pthreads){  int rc;  pthread_t tid1, tid2;  fail_if(pthread_mutex_init(&m, NULL) != 0);  fail_if(pthread_mutex_lock(&m) != 0);  fail_if(pthread_create(&tid1, NULL, threadproc__thread, (void*)0) != 0);  fail_if(pthread_create(&tid2, NULL, threadproc__thread, (void*)1) != 0);  fail_if(pthread_mutex_unlock(&m) != 0);  fail_if(pthread_join(tid1, NULL) != 0);  fail_if(pthread_join(tid2, NULL) != 0);  fail_if(results[0] == results[1]);  fail_if(pthread_mutex_destroy(&m) != 0);}END_TESTSuite* mt_suite(){  Suite *s = suite_create("Different multithreading techniques");  TCase *tc_core = tcase_create("Core");  tcase_add_test(tc_core, test_static_with_pthreads);  tcase_add_test(tc_core, test_thread_with_pthreads);  suite_add_tcase(s, tc_core);  return s;}int main(){  int number_failed;  Suite *s = mt_suite();  SRunner *sr = srunner_create(s);  srunner_set_fork_status(sr, CK_NOFORK);  srunner_run_all(sr, CK_VERBOSE);  number_failed = srunner_ntests_failed(sr);  srunner_free(sr);  return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;}