Boss::Boss(boost::shared_ptr<AL::ALBroker> broker_, const std::string &name) : AL::ALModule(broker_, name), broker(broker_), dcm(broker->getDcmProxy()), sensor(broker), enactor(dcm), led(broker), manPID(-1), manRunning(false), shared_fd(-1), shared(NULL), cmndLockMiss(0), sensorLockMiss(0), fifo_fd(-1) { printf("\t\tboss 7/%d\n", BOSS_VERSION); std::cout << "Boss Constructor" << std::endl; bool success = true; if ( pthread_mutexattr_init(&shared_mutex_attr) || pthread_mutexattr_setpshared(&shared_mutex_attr, PTHREAD_PROCESS_SHARED) ) { std::cout << "ERROR constructing shared process mutex attributes!" << std::endl; success = false; } if ( constructSharedMem() ) { std::cout << "Couldn't construct shared mem, oh well!" << std::endl; return; } // Link up to the DCM loop try { dcmPreProcessConnection = broker_->getProxy("DCM")->getModule()->atPreProcess( boost::bind(&Boss::DCMPreProcessCallback, this)); } catch(const AL::ALError& e) { std::cout << "Tried to bind preprocess, but failed, because " + e.toString() << std::endl; success = false; } try { dcmPostProcessConnection = broker_->getProxy("DCM")->getModule()->atPostProcess( boost::bind(&Boss::DCMPostProcessCallback, this)); } catch(const AL::ALError& e) { std::cout << "Tried to bind postprocess, but failed, because " + e.toString() << std::endl; success = false; } // The FIFO that we're going to listen for terminal commands on fifo_fd = open("/home/nao/nbites/nbitesFIFO", O_RDONLY | O_NONBLOCK); if (fifo_fd <= 0) { std::cout << "FIFO ERROR" << std::endl; std::cout << "Boss will not be able to receive commands from terminal" << std::endl; success = false; } if (success) { std::cout << "Boss Constructed successfully!" << std::endl; } else { std::cout << "\nWARNING: one or more errors while constructing Boss! Crash likely." << std::endl; } startMan(); // This will not return. listener(); }
int main (int argc, char *argv[]) { int i = 0; CRITICAL_SECTION cs; old_mutex_t ox; pthread_mutexattr_init(&ma); printf( "=============================================================================\n"); printf( "\nLock plus unlock on an unlocked mutex.\n%ld iterations\n\n", ITERATIONS); printf( "%-45s %15s %15s\n", "Test", "Total(msec)", "average(usec)"); printf( "-----------------------------------------------------------------------------\n"); /* * Time the loop overhead so we can subtract it from the actual test times. */ TESTSTART assert(1 == one); assert(1 == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; overHeadMilliSecs = durationMilliSecs; TESTSTART assert((dummy_call(&i), 1) == one); assert((dummy_call(&i), 1) == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Dummy call x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); TESTSTART assert((interlocked_inc_with_conditionals(&i), 1) == one); assert((interlocked_dec_with_conditionals(&i), 1) == one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Dummy call -> Interlocked with cond x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); TESTSTART assert((InterlockedIncrement((LPLONG)&i), 1) == (LONG)one); assert((InterlockedDecrement((LPLONG)&i), 1) == (LONG)one); TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "InterlockedOp x 2", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); InitializeCriticalSection(&cs); TESTSTART assert((EnterCriticalSection(&cs), 1) == one); assert((LeaveCriticalSection(&cs), 1) == one); TESTSTOP DeleteCriticalSection(&cs); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Simple Critical Section", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); old_mutex_use = OLD_WIN32CS; assert(old_mutex_init(&ox, NULL) == 0); TESTSTART assert(old_mutex_lock(&ox) == zero); assert(old_mutex_unlock(&ox) == zero); TESTSTOP assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Critical Section (WNT)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); old_mutex_use = OLD_WIN32MUTEX; assert(old_mutex_init(&ox, NULL) == 0); TESTSTART assert(old_mutex_lock(&ox) == zero); assert(old_mutex_unlock(&ox) == zero); TESTSTOP assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Win32 Mutex (W9x)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); printf( ".............................................................................\n"); /* * Now we can start the actual tests */ #ifdef PTW32_MUTEX_TYPES runTest("PTHREAD_MUTEX_DEFAULT (W9x,WNT)", PTHREAD_MUTEX_DEFAULT); runTest("PTHREAD_MUTEX_NORMAL (W9x,WNT)", PTHREAD_MUTEX_NORMAL); runTest("PTHREAD_MUTEX_ERRORCHECK (W9x,WNT)", PTHREAD_MUTEX_ERRORCHECK); runTest("PTHREAD_MUTEX_RECURSIVE (W9x,WNT)", PTHREAD_MUTEX_RECURSIVE); #else runTest("Non-blocking lock", 0); #endif printf( "=============================================================================\n"); /* * End of tests. */ pthread_mutexattr_destroy(&ma); one = i; /* Dummy assignment to avoid 'variable unused' warning */ return 0; }
int guac_client_init(guac_client* client, int argc, char** argv) { rdp_guac_client_data* guac_client_data; guac_rdp_settings* settings; freerdp* rdp_inst; /* Validate number of arguments received */ if (argc != RDP_ARGS_COUNT) { guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Wrong argument count received."); return 1; } /* Allocate client data */ guac_client_data = malloc(sizeof(rdp_guac_client_data)); /* Init random number generator */ srandom(time(NULL)); /* Init client */ #ifdef HAVE_FREERDP_CHANNELS_GLOBAL_INIT freerdp_channels_global_init(); #endif rdp_inst = freerdp_new(); rdp_inst->PreConnect = rdp_freerdp_pre_connect; rdp_inst->PostConnect = rdp_freerdp_post_connect; rdp_inst->Authenticate = rdp_freerdp_authenticate; rdp_inst->VerifyCertificate = rdp_freerdp_verify_certificate; rdp_inst->ReceiveChannelData = __guac_receive_channel_data; /* Allocate FreeRDP context */ #ifdef LEGACY_FREERDP rdp_inst->context_size = sizeof(rdp_freerdp_context); #else rdp_inst->ContextSize = sizeof(rdp_freerdp_context); #endif rdp_inst->ContextNew = (pContextNew) rdp_freerdp_context_new; rdp_inst->ContextFree = (pContextFree) rdp_freerdp_context_free; freerdp_context_new(rdp_inst); /* Set settings */ settings = &(guac_client_data->settings); /* Console */ settings->console = (strcmp(argv[IDX_CONSOLE], "true") == 0); settings->console_audio = (strcmp(argv[IDX_CONSOLE_AUDIO], "true") == 0); /* Certificate and auth */ settings->ignore_certificate = (strcmp(argv[IDX_IGNORE_CERT], "true") == 0); settings->disable_authentication = (strcmp(argv[IDX_DISABLE_AUTH], "true") == 0); /* NLA security */ if (strcmp(argv[IDX_SECURITY], "nla") == 0) { guac_client_log(client, GUAC_LOG_INFO, "Security mode: NLA"); settings->security_mode = GUAC_SECURITY_NLA; } /* TLS security */ else if (strcmp(argv[IDX_SECURITY], "tls") == 0) { guac_client_log(client, GUAC_LOG_INFO, "Security mode: TLS"); settings->security_mode = GUAC_SECURITY_TLS; } /* RDP security */ else if (strcmp(argv[IDX_SECURITY], "rdp") == 0) { guac_client_log(client, GUAC_LOG_INFO, "Security mode: RDP"); settings->security_mode = GUAC_SECURITY_RDP; } /* ANY security (allow server to choose) */ else if (strcmp(argv[IDX_SECURITY], "any") == 0) { guac_client_log(client, GUAC_LOG_INFO, "Security mode: ANY"); settings->security_mode = GUAC_SECURITY_ANY; } /* If nothing given, default to RDP */ else { guac_client_log(client, GUAC_LOG_INFO, "No security mode specified. Defaulting to RDP."); settings->security_mode = GUAC_SECURITY_RDP; } /* Set hostname */ settings->hostname = strdup(argv[IDX_HOSTNAME]); /* If port specified, use it */ settings->port = RDP_DEFAULT_PORT; if (argv[IDX_PORT][0] != '\0') settings->port = atoi(argv[IDX_PORT]); guac_client_log(client, GUAC_LOG_DEBUG, "Client resolution is %ix%i at %i DPI", client->info.optimal_width, client->info.optimal_height, client->info.optimal_resolution); /* Use suggested resolution unless overridden */ settings->resolution = guac_rdp_suggest_resolution(client); if (argv[IDX_DPI][0] != '\0') settings->resolution = atoi(argv[IDX_DPI]); /* Use optimal width unless overridden */ settings->width = client->info.optimal_width * settings->resolution / client->info.optimal_resolution; if (argv[IDX_WIDTH][0] != '\0') settings->width = atoi(argv[IDX_WIDTH]); /* Use default width if given width is invalid. */ if (settings->width <= 0) { settings->width = RDP_DEFAULT_WIDTH; guac_client_log(client, GUAC_LOG_ERROR, "Invalid width: \"%s\". Using default of %i.", argv[IDX_WIDTH], settings->width); } /* Round width down to nearest multiple of 4 */ settings->width = settings->width & ~0x3; /* Use optimal height unless overridden */ settings->height = client->info.optimal_height * settings->resolution / client->info.optimal_resolution; if (argv[IDX_HEIGHT][0] != '\0') settings->height = atoi(argv[IDX_HEIGHT]); /* Use default height if given height is invalid. */ if (settings->height <= 0) { settings->height = RDP_DEFAULT_HEIGHT; guac_client_log(client, GUAC_LOG_ERROR, "Invalid height: \"%s\". Using default of %i.", argv[IDX_WIDTH], settings->height); } guac_client_log(client, GUAC_LOG_DEBUG, "Using resolution of %ix%i at %i DPI", settings->width, settings->height, settings->resolution); /* Domain */ settings->domain = NULL; if (argv[IDX_DOMAIN][0] != '\0') settings->domain = strdup(argv[IDX_DOMAIN]); /* Username */ settings->username = NULL; if (argv[IDX_USERNAME][0] != '\0') settings->username = strdup(argv[IDX_USERNAME]); /* Password */ settings->password = NULL; if (argv[IDX_PASSWORD][0] != '\0') settings->password = strdup(argv[IDX_PASSWORD]); /* Client name */ settings->client_name = NULL; if (argv[IDX_CLIENT_NAME][0] != '\0') settings->client_name = strdup(argv[IDX_CLIENT_NAME]); /* Initial program */ settings->initial_program = NULL; if (argv[IDX_INITIAL_PROGRAM][0] != '\0') settings->initial_program = strdup(argv[IDX_INITIAL_PROGRAM]); /* RemoteApp program */ settings->remote_app = NULL; if (argv[IDX_REMOTE_APP][0] != '\0') settings->remote_app = strdup(argv[IDX_REMOTE_APP]); /* RemoteApp working directory */ settings->remote_app_dir = NULL; if (argv[IDX_REMOTE_APP_DIR][0] != '\0') settings->remote_app_dir = strdup(argv[IDX_REMOTE_APP_DIR]); /* RemoteApp arguments */ settings->remote_app_args = NULL; if (argv[IDX_REMOTE_APP_ARGS][0] != '\0') settings->remote_app_args = strdup(argv[IDX_REMOTE_APP_ARGS]); /* Static virtual channels */ settings->svc_names = NULL; if (argv[IDX_STATIC_CHANNELS][0] != '\0') settings->svc_names = guac_split(argv[IDX_STATIC_CHANNELS], ','); /* Performance flags */ settings->wallpaper_enabled = (strcmp(argv[IDX_ENABLE_WALLPAPER], "true") == 0); settings->theming_enabled = (strcmp(argv[IDX_ENABLE_THEMING], "true") == 0); settings->font_smoothing_enabled = (strcmp(argv[IDX_ENABLE_FONT_SMOOTHING], "true") == 0); settings->full_window_drag_enabled = (strcmp(argv[IDX_ENABLE_FULL_WINDOW_DRAG], "true") == 0); settings->desktop_composition_enabled = (strcmp(argv[IDX_ENABLE_DESKTOP_COMPOSITION], "true") == 0); settings->menu_animations_enabled = (strcmp(argv[IDX_ENABLE_MENU_ANIMATIONS], "true") == 0); /* Session color depth */ settings->color_depth = RDP_DEFAULT_DEPTH; if (argv[IDX_COLOR_DEPTH][0] != '\0') settings->color_depth = atoi(argv[IDX_COLOR_DEPTH]); /* Use default depth if given depth is invalid. */ if (settings->color_depth == 0) { settings->color_depth = RDP_DEFAULT_DEPTH; guac_client_log(client, GUAC_LOG_ERROR, "Invalid color-depth: \"%s\". Using default of %i.", argv[IDX_WIDTH], settings->color_depth); } /* Audio enable/disable */ guac_client_data->settings.audio_enabled = (strcmp(argv[IDX_DISABLE_AUDIO], "true") != 0); /* Printing enable/disable */ guac_client_data->settings.printing_enabled = (strcmp(argv[IDX_ENABLE_PRINTING], "true") == 0); /* Drive enable/disable */ guac_client_data->settings.drive_enabled = (strcmp(argv[IDX_ENABLE_DRIVE], "true") == 0); guac_client_data->settings.drive_path = strdup(argv[IDX_DRIVE_PATH]); guac_client_data->settings.create_drive_path = (strcmp(argv[IDX_CREATE_DRIVE_PATH], "true") == 0); /* Store client data */ guac_client_data->rdp_inst = rdp_inst; guac_client_data->mouse_button_mask = 0; guac_client_data->clipboard = guac_common_clipboard_alloc(GUAC_RDP_CLIPBOARD_MAX_LENGTH); guac_client_data->requested_clipboard_format = CB_FORMAT_TEXT; guac_client_data->audio = NULL; guac_client_data->filesystem = NULL; guac_client_data->available_svc = guac_common_list_alloc(); /* Main socket needs to be threadsafe */ guac_socket_require_threadsafe(client->socket); /* Recursive attribute for locks */ pthread_mutexattr_init(&(guac_client_data->attributes)); pthread_mutexattr_settype(&(guac_client_data->attributes), PTHREAD_MUTEX_RECURSIVE); /* Init RDP lock */ pthread_mutex_init(&(guac_client_data->rdp_lock), &(guac_client_data->attributes)); /* Clear keysym state mapping and keymap */ memset(guac_client_data->keysym_state, 0, sizeof(guac_rdp_keysym_state_map)); memset(guac_client_data->keymap, 0, sizeof(guac_rdp_static_keymap)); client->data = guac_client_data; ((rdp_freerdp_context*) rdp_inst->context)->client = client; /* Pick keymap based on argument */ settings->server_layout = NULL; if (argv[IDX_SERVER_LAYOUT][0] != '\0') settings->server_layout = guac_rdp_keymap_find(argv[IDX_SERVER_LAYOUT]); /* If no keymap requested, use default */ if (settings->server_layout == NULL) settings->server_layout = guac_rdp_keymap_find(GUAC_DEFAULT_KEYMAP); /* Load keymap into client */ __guac_rdp_client_load_keymap(client, settings->server_layout); #ifdef ENABLE_COMMON_SSH guac_common_ssh_init(client); /* Connect via SSH if SFTP is enabled */ if (strcmp(argv[IDX_ENABLE_SFTP], "true") == 0) { guac_client_log(client, GUAC_LOG_DEBUG, "Connecting via SSH for SFTP filesystem access."); /* Parse username - use RDP username by default */ const char* sftp_username = argv[IDX_SFTP_USERNAME]; if (sftp_username[0] == '\0' && settings->username != NULL) sftp_username = settings->username; guac_client_data->sftp_user = guac_common_ssh_create_user(sftp_username); /* Import private key, if given */ if (argv[IDX_SFTP_PRIVATE_KEY][0] != '\0') { guac_client_log(client, GUAC_LOG_DEBUG, "Authenticating with private key."); /* Abort if private key cannot be read */ if (guac_common_ssh_user_import_key(guac_client_data->sftp_user, argv[IDX_SFTP_PRIVATE_KEY], argv[IDX_SFTP_PASSPHRASE])) { guac_common_ssh_destroy_user(guac_client_data->sftp_user); return 1; } } /* Otherwise, use specified password */ else { guac_client_log(client, GUAC_LOG_DEBUG, "Authenticating with password."); /* Parse password - use RDP password by default */ const char* sftp_password = argv[IDX_SFTP_PASSWORD]; if (sftp_password[0] == '\0' && settings->password != NULL) sftp_password = settings->password; guac_common_ssh_user_set_password(guac_client_data->sftp_user, sftp_password); } /* Parse hostname - use RDP hostname by default */ const char* sftp_hostname = argv[IDX_SFTP_HOSTNAME]; if (sftp_hostname[0] == '\0') sftp_hostname = settings->hostname; /* Parse port, defaulting to standard SSH port */ const char* sftp_port = argv[IDX_SFTP_PORT]; if (sftp_port[0] == '\0') sftp_port = "22"; /* Attempt SSH connection */ guac_client_data->sftp_session = guac_common_ssh_create_session(client, sftp_hostname, sftp_port, guac_client_data->sftp_user); /* Fail if SSH connection does not succeed */ if (guac_client_data->sftp_session == NULL) { /* Already aborted within guac_common_ssh_create_session() */ guac_common_ssh_destroy_user(guac_client_data->sftp_user); return 1; } /* Load and expose filesystem */ guac_client_data->sftp_filesystem = guac_common_ssh_create_sftp_filesystem( guac_client_data->sftp_session, "/"); /* Abort if SFTP connection fails */ if (guac_client_data->sftp_filesystem == NULL) { guac_common_ssh_destroy_session(guac_client_data->sftp_session); guac_common_ssh_destroy_user(guac_client_data->sftp_user); return 1; } /* Configure destination for basic uploads, if specified */ if (argv[IDX_SFTP_DIRECTORY][0] != '\0') { client->file_handler = guac_rdp_sftp_file_handler; guac_common_ssh_sftp_set_upload_path( guac_client_data->sftp_filesystem, argv[IDX_SFTP_DIRECTORY]); } /* Otherwise, use SFTP for basic uploads only if drive not enabled */ else if (!settings->drive_enabled) client->file_handler = guac_rdp_sftp_file_handler; guac_client_log(client, GUAC_LOG_DEBUG, "SFTP connection succeeded."); } #endif /* Create default surface */ guac_client_data->default_surface = guac_common_surface_alloc(client, client->socket, GUAC_DEFAULT_LAYER, settings->width, settings->height); guac_client_data->current_surface = guac_client_data->default_surface; /* Send connection name */ guac_protocol_send_name(client->socket, settings->hostname); /* Set default pointer */ guac_common_set_pointer_cursor(client); /* Push desired settings to FreeRDP */ guac_rdp_push_settings(settings, rdp_inst); /* Connect to RDP server */ if (!freerdp_connect(rdp_inst)) { guac_client_abort(client, GUAC_PROTOCOL_STATUS_UPSTREAM_ERROR, "Error connecting to RDP server"); return 1; } /* Success */ return 0; }
int dcethread_mutexattr_create(dcethread_mutexattr *attr) { return dcethread__set_errno(pthread_mutexattr_init(attr)); }
//sem_getvalue on a semaphore waited on n times TInt CTestSemgetvalue::TestSem318( ) { int retval = 0; int errsum=0, err = 0; ThreadData lThreadData; sem_t lSignalSemaphore; sem_t lSuspendSemaphore; sem_t lTestSemaphore; pthread_mutex_t lTestMutex; pthread_cond_t lTestCondVar; pthread_condattr_t lCondAttr; pthread_mutexattr_t lTestMutexAttr; pthread_mutexattr_t defaultattr; pthread_mutexattr_t errorcheckattr; pthread_mutexattr_t recursiveattr; pthread_mutexattr_init(&defaultattr); pthread_mutexattr_init(&errorcheckattr); pthread_mutexattr_init(&recursiveattr); pthread_mutexattr_settype(&errorcheckattr,PTHREAD_MUTEX_ERRORCHECK); pthread_mutexattr_settype(&recursiveattr,PTHREAD_MUTEX_RECURSIVE); pthread_mutex_t l_staticmutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t l_errorcheckmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; pthread_mutex_t l_recursivemutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; pthread_cond_t l_staticcondvar = PTHREAD_COND_INITIALIZER; CommonData lCommonData; lCommonData.iStaticMutex = &l_staticmutex; lCommonData.iErrorCheckMutex = &l_errorcheckmutex; lCommonData.iRecursiveMutex = &l_recursivemutex; lCommonData.iStaticCondVar = &l_staticcondvar; retval = sem_init(&lSignalSemaphore,0,0); if(retval != 0) { return retval; } retval = sem_init(&lSuspendSemaphore,0,0); if(retval != 0) { return retval; } lThreadData.iSignalSemaphore = &lSignalSemaphore; lThreadData.iSuspendSemaphore = &lSuspendSemaphore; lThreadData.iTestSemaphore = &lTestSemaphore; lThreadData.iTestMutex = &lTestMutex; lThreadData.iTestMutexAttr = &lTestMutexAttr; lThreadData.iTestCondVar = &lTestCondVar; lThreadData.iDefaultAttr = &defaultattr; lThreadData.iErrorcheckAttr = &errorcheckattr; lThreadData.iRecursiveAttr = &recursiveattr; lThreadData.iCondAttr = &lCondAttr; for (int loop = 0; loop < EThreadMain; loop++) { g_spinFlag[loop] = true; } lThreadData.iSuspending = false; lThreadData.iSpinCounter = 0; lThreadData.iCurrentCommand = -1; lThreadData.iSelf = EThreadMain; lThreadData.iValue = 0; lThreadData.iRetValue = 0; lThreadData.ierrno = 0; lThreadData.iExpectederrno = 0; lThreadData.iTimes = 0; lThreadData.iStopped = false; lThreadData.iCommonData = &lCommonData; retval = SemInit(&lThreadData); fp=func1; retval = ThreadCreate(&lThreadData, (void*) EThread1); fp=func2; retval = ThreadCreate(&lThreadData, (void*) EThread2); fp=func3; retval = ThreadCreate(&lThreadData, (void*) EThread3); fp=func4; retval = ThreadCreate(&lThreadData, (void*) EThread4); WaitTillSuspended(&lThreadData, (void*) EThread1); WaitTillSuspended(&lThreadData, (void*) EThread2); WaitTillSuspended(&lThreadData, (void*) EThread3); WaitTillSuspended(&lThreadData, (void*) EThread4); retval = SemGetValue(&lThreadData); retval = CheckValue(&lThreadData,-4); retval = SemPost(&lThreadData); retval = SemPost(&lThreadData); retval = SemGetValue(&lThreadData); retval = CheckValue(&lThreadData,-2); retval = SemPost(&lThreadData); retval = SemPost(&lThreadData); retval = SemGetValue(&lThreadData); retval = ThreadDestroy(&lThreadData, (void*) EThread1); retval = ThreadDestroy(&lThreadData, (void*) EThread2); retval = ThreadDestroy(&lThreadData, (void*) EThread3); retval = ThreadDestroy(&lThreadData, (void*) EThread4); retval = SemDestroy(&lThreadData); StopThread(&lThreadData); err = pthread_cond_destroy(&l_staticcondvar); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_recursivemutex); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_errorcheckmutex); if(err != EINVAL) { errsum += err; } err = pthread_mutex_destroy(&l_staticmutex); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&recursiveattr); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&errorcheckattr); if(err != EINVAL) { errsum += err; } err = pthread_mutexattr_destroy(&defaultattr); if(err != EINVAL) { errsum += err; } err = sem_destroy(&lSignalSemaphore); if(err != EINVAL) { errsum += err; } err = sem_destroy(&lSuspendSemaphore); if(err != EINVAL) { errsum += err; } return retval+errsum; }
bool w_start_listener(const char *path) { pthread_mutexattr_t mattr; #ifndef _WIN32 struct sigaction sa; sigset_t sigset; #endif void *ignored; #ifdef HAVE_LIBGIMLI_H volatile struct gimli_heartbeat *hb = NULL; #endif struct timeval tv; int n_clients = 0; listener_thread = pthread_self(); pthread_mutexattr_init(&mattr); pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&w_client_lock, &mattr); pthread_mutexattr_destroy(&mattr); #ifdef HAVE_LIBGIMLI_H hb = gimli_heartbeat_attach(); #endif #if defined(HAVE_KQUEUE) || defined(HAVE_FSEVENTS) { struct rlimit limit; # ifndef __OpenBSD__ int mib[2] = { CTL_KERN, # ifdef KERN_MAXFILESPERPROC KERN_MAXFILESPERPROC # else KERN_MAXFILES # endif }; # endif int maxperproc; getrlimit(RLIMIT_NOFILE, &limit); # ifndef __OpenBSD__ size_t len; len = sizeof(maxperproc); sysctl(mib, 2, &maxperproc, &len, NULL, 0); w_log(W_LOG_ERR, "file limit is %" PRIu64 " kern.maxfilesperproc=%i\n", limit.rlim_cur, maxperproc); # else maxperproc = limit.rlim_max; w_log(W_LOG_ERR, "openfiles-cur is %" PRIu64 " openfiles-max=%i\n", limit.rlim_cur, maxperproc); # endif if (limit.rlim_cur != RLIM_INFINITY && maxperproc > 0 && limit.rlim_cur < (rlim_t)maxperproc) { limit.rlim_cur = maxperproc; if (setrlimit(RLIMIT_NOFILE, &limit)) { w_log(W_LOG_ERR, "failed to raise limit to %" PRIu64 " (%s).\n", limit.rlim_cur, strerror(errno)); } else { w_log(W_LOG_ERR, "raised file limit to %" PRIu64 "\n", limit.rlim_cur); } } getrlimit(RLIMIT_NOFILE, &limit); #ifndef HAVE_FSEVENTS if (limit.rlim_cur < 10240) { w_log(W_LOG_ERR, "Your file descriptor limit is very low (%" PRIu64 "), " "please consult the watchman docs on raising the limits\n", limit.rlim_cur); } #endif } #endif proc_pid = (int)getpid(); if (gettimeofday(&tv, NULL) == -1) { w_log(W_LOG_ERR, "gettimeofday failed: %s\n", strerror(errno)); return false; } proc_start_time = (uint64_t)tv.tv_sec; #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); /* allow SIGUSR1 and SIGCHLD to wake up a blocked thread, without restarting * syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = wakeme; sa.sa_flags = 0; sigaction(SIGUSR1, &sa, NULL); sigaction(SIGCHLD, &sa, NULL); // Block SIGCHLD everywhere sigemptyset(&sigset); sigaddset(&sigset, SIGCHLD); sigprocmask(SIG_BLOCK, &sigset, NULL); listener_fd = get_listener_socket(path); if (listener_fd == -1) { return false; } w_set_cloexec(listener_fd); #endif if (pthread_create(&reaper_thread, NULL, child_reaper, NULL)) { w_log(W_LOG_FATAL, "pthread_create(reaper): %s\n", strerror(errno)); return false; } if (!clients) { clients = w_ht_new(2, &client_hash_funcs); } w_state_load(); #ifdef HAVE_LIBGIMLI_H if (hb) { gimli_heartbeat_set(hb, GIMLI_HB_RUNNING); } else { w_setup_signal_handlers(); } #else w_setup_signal_handlers(); #endif w_set_nonblock(listener_fd); // Now run the dispatch #ifndef _WIN32 accept_loop(); #else named_pipe_accept_loop(path); #endif #ifndef _WIN32 /* close out some resources to persuade valgrind to run clean */ close(listener_fd); listener_fd = -1; #endif // Wait for clients, waking any sleeping clients up in the process do { w_ht_iter_t iter; pthread_mutex_lock(&w_client_lock); n_clients = w_ht_size(clients); if (w_ht_first(clients, &iter)) do { struct watchman_client *client = w_ht_val_ptr(iter.value); w_event_set(client->ping); } while (w_ht_next(clients, &iter)); pthread_mutex_unlock(&w_client_lock); w_log(W_LOG_ERR, "waiting for %d clients to terminate\n", n_clients); usleep(2000); } while (n_clients > 0); w_root_free_watched_roots(); pthread_join(reaper_thread, &ignored); cfg_shutdown(); return true; }
void errl_Init ( const char *termName, void (*log_cb)( void *, char *, char, pwr_tStatus, int, int), void *userdata ) { pthread_mutexattr_t mutexattr; pthread_attr_t pthreadattr; struct mq_attr mqattr; mode_t mode; int oflags; char name[64]; char *busid = getenv(pwr_dEnvBusId); static int initDone = 0; int policy; struct sched_param param; errl_log_cb = log_cb; errl_log_userdata = userdata; if (initDone) return; if ((pthread_getschedparam(pthread_self(), &policy, ¶m)) == -1) { perror("rt_errl: pthread_getprio(pthread_self() "); return; } pthread_mutexattr_init(&mutexattr); if (pthread_mutex_init(&fileMutex, &mutexattr) == -1) { perror("rt_logmod: pthread_mutex_init(&fileMutex, mutexattr) "); return; } if (pthread_mutex_init(&termMutex, &mutexattr) == -1) { perror("rt_logmod: pthread_mutex_init(&termMutex, mutexattr) "); return; } pthread_mutexattr_destroy(&mutexattr); mqattr.mq_msgsize = LOG_MAX_MSG_SIZE; /* max mess size */ mqattr.mq_maxmsg = MAX_NO_MSG; /* max no of msg in this queue */ mqattr.mq_flags = 0; // O_NONBLOCK; oflags = O_CREAT | O_RDWR; mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; sprintf(name, "%s_%s", LOG_QUEUE_NAME, busid ? busid : ""); mqid = mq_open(name, oflags, mode, &mqattr); if (mqid == (mqd_t)-1) { if (errno == EINVAL) { mqattr.mq_maxmsg = DEF_MAX_NO_MSG; /* Try with smaller queue */ mqid = mq_open(name, oflags, mode, &mqattr); if (mqid == (mqd_t)-1) { perror("rt_logmod: mq_open "); return; } } else { perror("rt_logmod: mq_open "); return; } } pthread_attr_init(&pthreadattr); if (pthread_create(&tid, &pthreadattr, log_thread, NULL) == -1) { perror("rt_logmod: pthread_create "); pthread_attr_destroy(&pthreadattr); return; } pthread_attr_destroy(&pthreadattr); param.sched_priority -= 1; pthread_setschedparam(tid, policy, ¶m); if (termName && *termName) errl_SetTerm(termName); logToStdout = getenv("PWR_LOG_TO_STDOUT") != NULL ? TRUE : FALSE; initDone = 1; return; }
mutex(int type = PTHREAD_MUTEX_DEFAULT) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, type); pthread_mutex_init(&_mutex, &attr); }
int pthread_mutexattr_test(void){ pthread_mutexattr_t attr; int tmp; int i; printf("Test pthread_mutexattr_init()..."); if ( pthread_mutexattr_init(&attr) < 0 ){ fflush(stdout); perror("failed"); return -1; } printf("passed\n"); printf("Test pthread_mutexattr_set/getprioceiling()..."); for(i = sched_get_priority_min(SCHED_OTHER); i <= sched_get_priority_max(SCHED_OTHER); i++ ){ if ( pthread_mutexattr_setprioceiling(&attr, i) < 0 ){ fflush(stdout); perror("failed"); return -1; } if ( pthread_mutexattr_getprioceiling(&attr, &tmp) < 0 ){ fflush(stdout); perror("failed"); return -1; } if ( tmp != i ){ printf("failed to set/get (%d != %d)\n", tmp, i); return -1; } } printf("passed\n"); if ( set_get_test("pthread_mutexattr_set/getprotocol()", (int (*)(void*,int))pthread_mutexattr_setprotocol, (int (*)(void*,int*))pthread_mutexattr_getprotocol, &attr, protocols, PROTOCOLS_TOTAL, 0) ){ return -1; } printf("Test pthread_mutexattr_set/getpshared()..."); tmp = 1; if ( pthread_mutexattr_setpshared(&attr, tmp) < 0 ){ fflush(stdout); perror("failed"); return -1; } if ( pthread_mutexattr_getpshared(&attr, &tmp) < 0 ){ fflush(stdout); perror("failed"); return -1; } if ( tmp != 1 ){ fflush(stdout); perror("failed"); return -1; } printf("passed\n"); if ( set_get_test("pthread_mutexattr_set/gettype()", (int (*)(void*,int))pthread_mutexattr_settype, (int (*)(void*,int*))pthread_mutexattr_gettype, &attr, types, TYPES_TOTAL, 0) ){ return -1; } printf("Test pthread_mutexattr_destroy()..."); if ( pthread_mutexattr_destroy(&attr) < 0 ){ fflush(stdout); perror("failed"); return -1; } printf("passed\n"); printf("Stress Test pthread_mutexattr_destroy()..."); if ( pthread_mutexattr_destroy(&attr) == 0 ){ printf("should have failed\n"); return -1; } errno = 0; printf("passed\n"); return 0; }
static void init() { int i, n, size; static int block_count_tab[3] = {6,8,12}; int lum_buffer_size, chrom_buffer_size; pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutex_init(&test_lock, &mutex_attr); bzero(&cur_picture, sizeof(pict_data_s)); mpeg2_initbits(); init_fdct(); init_idct(); init_motion(); init_predict_hv(); init_quantizer_hv(); init_transform_hv(); /* round picture dimensions to nZearest multiple of 16 or 32 */ mb_width = (horizontal_size+15)/16; mb_height = prog_seq ? (vertical_size + 15) / 16 : 2 * ((vertical_size + 31) / 32); mb_height2 = fieldpic ? mb_height >> 1 : mb_height; /* for field pictures */ width = 16 * mb_width; height = 16 * mb_height; chrom_width = (chroma_format==CHROMA444) ? width : width>>1; chrom_height = (chroma_format!=CHROMA420) ? height : height>>1; height2 = fieldpic ? height>>1 : height; width2 = fieldpic ? width<<1 : width; chrom_width2 = fieldpic ? chrom_width<<1 : chrom_width; block_count = block_count_tab[chroma_format-1]; lum_buffer_size = (width*height) + sizeof(uint8_t) *(width/2)*(height/2) + sizeof(uint8_t) *(width/4)*(height/4+1); chrom_buffer_size = chrom_width*chrom_height; fsubsample_offset = (width)*(height) * sizeof(uint8_t); qsubsample_offset = fsubsample_offset + (width/2)*(height/2)*sizeof(uint8_t); rowsums_offset = 0; colsums_offset = 0; mb_per_pict = mb_width*mb_height2; /* clip table */ if (!(clp = (unsigned char *)malloc(1024))) error("malloc failed\n"); clp+= 384; for (i=-384; i<640; i++) clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i); /* Allocate the frame buffer */ frame_buffers = (uint8_t ***) bufalloc(2*READ_LOOK_AHEAD*sizeof(uint8_t**)); for(n=0;n<2*READ_LOOK_AHEAD;n++) { frame_buffers[n] = (uint8_t **) bufalloc(3*sizeof(uint8_t*)); for (i=0; i<3; i++) { frame_buffers[n][i] = bufalloc( (i==0) ? lum_buffer_size : chrom_buffer_size ); } } /* TODO: The ref and aux frame buffers are no redundant! */ for( i = 0 ; i<3; i++) { int size = (i==0) ? lum_buffer_size : chrom_buffer_size; newrefframe[i] = bufalloc(size); oldrefframe[i] = bufalloc(size); auxframe[i] = bufalloc(size); predframe[i] = bufalloc(size); } cur_picture.qblocks = (int16_t (*)[64])bufalloc(mb_per_pict*block_count*sizeof(int16_t [64])); /* Initialise current transformed picture data tables These will soon become a buffer for transformed picture data to allow look-ahead for bit allocation etc. */ cur_picture.mbinfo = ( struct mbinfo *)bufalloc(mb_per_pict*sizeof(struct mbinfo)); cur_picture.blocks = (int16_t (*)[64])bufalloc(mb_per_pict * block_count * sizeof(int16_t [64])); /* open statistics output file */ if(statname[0]=='-') statfile = stdout; else if(!(statfile = fopen(statname,"w"))) { sprintf(errortext,"Couldn't create statistics output file %s",statname); error(errortext); } ratectl = malloc(processors * sizeof(ratectl_t*)); for(i = 0; i < processors; i++) ratectl[i] = calloc(1, sizeof(ratectl_t)); /* Start parallel threads */ //printf("init 1\n"); start_motion_engines(); //printf("init 2\n"); start_transform_engines(); //printf("init 3\n"); start_itransform_engines(); //printf("init 4\n"); start_slice_engines(); //printf("init 5\n"); }
PTMutex() { pthread_mutexattr_init( &m_Attributes ); pthread_mutexattr_settype( &m_Attributes, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( &m_Mutex, &m_Attributes ); }
VCOS_STATUS_T vcos_timer_create(VCOS_TIMER_T *timer, const char *name, void (*expiration_routine)(void *context), void *context) { pthread_mutexattr_t lock_attr; VCOS_STATUS_T result = VCOS_SUCCESS; int settings_changed_initialized = 0; int lock_attr_initialized = 0; int lock_initialized = 0; (void)name; vcos_assert(timer); vcos_assert(expiration_routine); memset(timer, 0, sizeof(VCOS_TIMER_T)); timer->orig_expiration_routine = expiration_routine; timer->orig_context = context; /* Create conditional variable for notifying the timer's thread * when settings change. */ if (result == VCOS_SUCCESS) { int rc = pthread_cond_init(&timer->settings_changed, NULL); if (rc == 0) settings_changed_initialized = 1; else result = vcos_pthreads_map_error(rc); } /* Create attributes for the lock (we want it to be recursive) */ if (result == VCOS_SUCCESS) { int rc = pthread_mutexattr_init(&lock_attr); if (rc == 0) { pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE); lock_attr_initialized = 1; } else { result = vcos_pthreads_map_error(rc); } } /* Create lock for the timer structure */ if (result == VCOS_SUCCESS) { int rc = pthread_mutex_init(&timer->lock, &lock_attr); if (rc == 0) lock_initialized = 1; else result = vcos_pthreads_map_error(rc); } /* Lock attributes are no longer needed */ if (lock_attr_initialized) pthread_mutexattr_destroy(&lock_attr); /* Create the underlying thread */ if (result == VCOS_SUCCESS) { int rc = pthread_create(&timer->thread, NULL, _timer_thread, timer); if (rc != 0) result = vcos_pthreads_map_error(rc); } /* Clean up if anything went wrong */ if (result != VCOS_SUCCESS) { if (lock_initialized) pthread_mutex_destroy(&timer->lock); if (settings_changed_initialized) pthread_cond_destroy(&timer->settings_changed); } return result; }
int main (int argc, char *argv[]) { pthread_t t; assert(pthread_mutexattr_init(&ma) == 0); printf( "=============================================================================\n"); printf( "\nTrylock on a locked mutex.\n"); printf( "%ld iterations.\n\n", ITERATIONS); printf( "%-45s %15s %15s\n", "Test", "Total(msec)", "average(usec)"); printf( "-----------------------------------------------------------------------------\n"); /* * Time the loop overhead so we can subtract it from the actual test times. */ TESTSTART TESTSTOP durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; overHeadMilliSecs = durationMilliSecs; old_mutex_use = OLD_WIN32CS; assert(old_mutex_init(&ox, NULL) == 0); assert(old_mutex_lock(&ox) == 0); assert(pthread_create(&t, NULL, oldTrylockThread, 0) == 0); assert(pthread_join(t, NULL) == 0); assert(old_mutex_unlock(&ox) == 0); assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Critical Section (WNT)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); old_mutex_use = OLD_WIN32MUTEX; assert(old_mutex_init(&ox, NULL) == 0); assert(old_mutex_lock(&ox) == 0); assert(pthread_create(&t, NULL, oldTrylockThread, 0) == 0); assert(pthread_join(t, NULL) == 0); assert(old_mutex_unlock(&ox) == 0); assert(old_mutex_destroy(&ox) == 0); durationMilliSecs = GetDurationMilliSecs(currSysTimeStart, currSysTimeStop) - overHeadMilliSecs; printf( "%-45s %15ld %15.3f\n", "Old PT Mutex using a Win32 Mutex (W9x)", durationMilliSecs, (float) durationMilliSecs * 1E3 / ITERATIONS); printf( ".............................................................................\n"); /* * Now we can start the actual tests */ #ifdef PTW32_MUTEX_TYPES runTest("PTHREAD_MUTEX_DEFAULT (W9x,WNT)", PTHREAD_MUTEX_DEFAULT); runTest("PTHREAD_MUTEX_NORMAL (W9x,WNT)", PTHREAD_MUTEX_NORMAL); runTest("PTHREAD_MUTEX_ERRORCHECK (W9x,WNT)", PTHREAD_MUTEX_ERRORCHECK); runTest("PTHREAD_MUTEX_RECURSIVE (W9x,WNT)", PTHREAD_MUTEX_RECURSIVE); #else runTest("Non-blocking lock", 0); #endif printf( "=============================================================================\n"); /* * End of tests. */ pthread_mutexattr_destroy(&ma); return 0; }
Mutex::Mutex() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutex_init(&mutex_, &attr); }
void *POSIX_Init( void *ignored ) { int sc; pthread_mutexattr_t attr; int type; int i; puts( "\n\n*** POSIX MUTEX ATTRIBUTE TEST 1 ***" ); #if defined(_UNIX98_THREAD_MUTEX_ATTRIBUTES) puts( "Init - pthread_mutexattr_gettype - attr NULL - EINVAL" ); sc = pthread_mutexattr_gettype( NULL, &type ); rtems_test_assert( sc == EINVAL ); puts( "Init - pthread_mutexattr_gettype - type NULL - EINVAL" ); sc = pthread_mutexattr_gettype( &attr, NULL ); rtems_test_assert( sc == EINVAL ); memset( &attr, 0, sizeof(attr) ); puts( "Init - pthread_mutexattr_gettype - attr not initialized - EINVAL" ); sc = pthread_mutexattr_gettype( &attr, &type ); rtems_test_assert( sc == EINVAL ); puts( "Init - pthread_mutexattr_init - OK" ); sc = pthread_mutexattr_init( &attr ); rtems_test_assert( sc == 0 ); puts( "Init - pthread_mutexattr_gettype - OK" ); sc = pthread_mutexattr_gettype( &attr, &type ); rtems_test_assert( sc == 0 ); /* now do settype */ puts( "Init - pthread_mutexattr_settype - type NULL - EINVAL" ); sc = pthread_mutexattr_settype( NULL, PTHREAD_MUTEX_NORMAL ); rtems_test_assert( sc == EINVAL ); memset( &attr, 0, sizeof(attr) ); puts( "Init - pthread_mutexattr_settype - attr not initialized - EINVAL" ); sc = pthread_mutexattr_settype( NULL, PTHREAD_MUTEX_NORMAL ); rtems_test_assert( sc == EINVAL ); /* iterate over good/bad get sets */ for (i=0 ; i<TO_CHECK ; i++ ) { puts( "Init - pthread_mutexattr_init - OK" ); sc = pthread_mutexattr_init( &attr ); rtems_test_assert( sc == 0 ); printf( "Init - pthread_mutexattr_settype - %s\n", TypesToCheck[i].name ); sc = pthread_mutexattr_settype( &attr, TypesToCheck[i].type ); rtems_test_assert( sc == TypesToCheck[i].status ); type = -2; if ( TypesToCheck[i].status == 0 ) { printf( "Init - pthread_mutexattr_gettype - %s\n", TypesToCheck[i].name ); sc = pthread_mutexattr_gettype( &attr, &type ); rtems_test_assert( sc == 0 ); rtems_test_assert( type == TypesToCheck[i].type ); } } #else puts( "POSIX Mutex Attribute Type Not Supported in Tools" ); #endif puts( "*** END OF POSIX MUTEX ATTRIBUTE TEST 1 ***" ); rtems_test_exit(0); }
int main(int argc, char *argv[]) { pid_t child; pthread_mutex_t mtx; pthread_mutexattr_t ma[4]; pthread_mutexattr_t *pma[5]; int ret = 0; int i; int retini[5] = { -1, -1, -1, -1, -1 }; int retdtr[5] = { -1, -1, -1, -1, -1 }; void *ptr, *ptr_prev = NULL; int sz = 0; struct rlimit rl; int status = 0; output_init(); child = fork(); if (child == (pid_t) - 1) { UNRESOLVED(errno, "Fork failed"); } if (child != 0) { /* We are the father */ if (child != waitpid(child, &status, 0)) { UNRESOLVED(errno, "Waitpid failed"); } if (WIFSIGNALED(status)) { UNRESOLVED(WTERMSIG(status), "The child process was killed."); } if (WIFEXITED(status)) return WEXITSTATUS(status); UNRESOLVED(0, "Child process neither returned nor was killed."); } /* Only the child goes further */ /* We initialize the different mutex attributes */ for (i = 0; (i < 4) && (ret == 0); i++) { pma[i] = &ma[i]; ret = pthread_mutexattr_init(pma[i]); } if (ret) { UNRESOLVED(ret, "Mutex attribute init failed"); } pma[4] = (pthread_mutexattr_t *) NULL; if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_NORMAL))) { UNRESOLVED(ret, "Mutex attribute NORMAL failed"); } if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_DEFAULT))) { UNRESOLVED(ret, "Mutex attribute DEFAULT failed"); } if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_RECURSIVE))) { UNRESOLVED(ret, "Mutex attribute RECURSIVE failed"); } if ((ret = pthread_mutexattr_settype(pma[0], PTHREAD_MUTEX_ERRORCHECK))) { UNRESOLVED(ret, "Mutex attribute ERRORCHECK failed"); } sz = sysconf(_SC_PAGESIZE); /* Limit the process memory to a small value (64Mb for example). */ rl.rlim_max = 1024 * 1024 * 64; rl.rlim_cur = 1024 * 1024 * 64; if ((ret = setrlimit(RLIMIT_AS, &rl))) { UNRESOLVED(ret, "Memory limitation failed"); } #if VERBOSE > 1 output("Ready to take over memory. Page size is %d\n", sz); #endif /* Allocate all available memory */ while (1) { ptr = malloc(sz); /* Allocate one page of memory */ if (ptr == NULL) break; #if VERBOSE > 1 ret++; #endif *(void **)ptr = ptr_prev; /* Write into the allocated page */ ptr_prev = ptr; } #if VERBOSE > 1 output("%d pages were allocated before failure\n", ret); ret = 0; #endif while (1) { ptr = malloc(sizeof(void *)); /* Allocate every remaining bits of memory */ if (ptr == NULL) break; #if VERBOSE > 1 ret++; #endif *(void **)ptr = ptr_prev; /* Keep track of allocated memory */ ptr_prev = ptr; } #if VERBOSE > 1 output("%d additional spaces were allocated before failure\n", ret); ret = 0; #endif if (errno != ENOMEM) UNRESOLVED(errno, "Memory not full"); /* Now that memory is full, we try to initialize a mutex */ for (i = 0; i < 5; i++) { retini[i] = pthread_mutex_init(&mtx, pma[i]); if (!retini[i]) /* If mutex has been initialized, we destroy it */ retdtr[i] = pthread_mutex_destroy(&mtx); } /* We can now free the memory */ while (ptr_prev != NULL) { ptr = ptr_prev; ptr_prev = *(void **)ptr; free(ptr); } #if VERBOSE > 1 output("Memory is released\n"); #endif for (i = 0; i < 4; i++) pthread_mutexattr_destroy(pma[i]); for (i = 0; i < 5; i++) { if (retini[i] != 0 && retini[i] != ENOMEM) { FAILED ("Mutex init returned a wrong error code when no memory was left"); } if (retini[i] == 0) { #if VERBOSE > 0 output ("Mutex initialization for attribute %d succeeds when memory is full\n", i); #endif if (retdtr[i] != 0) { UNRESOLVED(retdtr[i], "Mutex destroy failed on mutex inilialized under heavy loaded memory"); } } #if VERBOSE > 0 else { output ("Mutex initialization for attribute %d fails with ENOMEM when memory is full\n", i); } #endif } PASSED; }
int main(int argc, char *argv[]){ /* TODO implement command line parameter parser */ int v; int listen_fd; int listen_address; struct sockaddr_in servaddr; pthread_t thread_id; pthread_attr_t attr; pthread_mutexattr_t mtx_attr; threadargs_t *t_args; reqargs_t *request; log_level = LOGDEBUG; log_fd = stdout; /* initialize the terminal output mutex before we start logging stuff */ if( pthread_mutexattr_init(&mtx_attr) != 0 || pthread_mutexattr_settype(&mtx_attr, PTHREAD_MUTEX_RECURSIVE) != 0 || pthread_mutex_init(&mtx_term, &mtx_attr) != 0 ) { printf("System error: unable to initialize terminal mutex"); exit(ERRSYS); } /* inet_pton(AF_INET, ADDRESS, &listen_address); */ listen_address = htonl(INADDR_ANY); /* set up a new socket for us to (eventually) listen us */ if( (listen_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { oct_panic(ERRSYS, "socket create error"); } else { oct_log(LOGINFO, "socket create success"); } /* setsocketopt() sets a socket option to allow multiple processes to listen. this is only needed during testing so we can quickly restart the server without waiting for the port to close. */ v = 1; if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &v, sizeof(v)) < 0) { oct_panic(ERRSYS, "setsockopt() failed"); } else { oct_log(LOGINFO, "setsockopt() SO_REUSEADDR success"); } /* set the server listening parameters: IPv4, IP address, port number */ servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(listen_address); servaddr.sin_port = htons(PORT); /* bind our socket to the specified address/port */ if( bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { oct_panic(ERRSYS, "socket error binding to %s", servaddr.sin_addr.s_addr == htonl(INADDR_ANY) ? "INADDR_ANY" : ADDRESS); } else { oct_log(LOGINFO, "socket bound to %s", servaddr.sin_addr.s_addr == htonl(INADDR_ANY) ? "INADDR_ANY" : ADDRESS); } /* set the socket to passive listening on the already-bound address/port */ if( listen(listen_fd, LISTENQ) < 0 ) { oct_panic(ERRSYS, "socket listen error on port %d", PORT); } else { oct_log(LOGINFO, "socket set to listen on port %d", PORT); } /* set up a thread attributes structure so we don't need an extra call to pthread_detach() */ if( pthread_attr_init(&attr) < 0 || pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) < 0) { oct_panic(ERRSYS, "error initializing thread attributes structure"); } else { oct_log(LOGDEBUG, "initialized thread attributes structure"); } /* save the size of the sockaddr structure since we need it held in a variable */ v = sizeof(struct sockaddr_in); /* enter our socket listen/accept() loop */ for(;;) { /* set up our thread argument structure. we need to pass the new connection descriptor and client address structure as well as create read and write buffers */ t_args = malloc(sizeof(threadargs_t)); t_args->request = malloc(sizeof(reqargs_t)); /* at the call to accept(), the main thread blocks until a client connects */ if( (t_args->conn_fd = accept(listen_fd, (struct sockaddr *) &(t_args->conn_info), (socklen_t*) &v)) < 0) { oct_panic(ERRSYS, "connection accept failure from client %s", inet_ntoa(t_args->conn_info.sin_addr)); } else { oct_log(LOGINFO, "accepted connection from client %s", inet_ntoa(t_args->conn_info.sin_addr)); } /* spawn a new thread to handle the accept()'ed connection */ if( (pthread_create(&thread_id, &attr, (void *(*)(void *)) oct_worker_thread, t_args)) < 0) { oct_panic(ERRSYS, "spawn connection thread failed with ID %d and address %s", thread_id, inet_ntoa(t_args->conn_info.sin_addr)); } } }
SEM_ID semMCreate(int options) { pthread_mutexattr_t mattr; struct wind_sem *sem; struct service svc; if (options & ~(SEM_Q_PRIORITY|SEM_DELETE_SAFE|SEM_INVERSION_SAFE)) { errno = S_semLib_INVALID_OPTION; return (SEM_ID)0; } if ((options & SEM_Q_PRIORITY) == 0) { if (options & SEM_INVERSION_SAFE) { errno = S_semLib_INVALID_QUEUE_TYPE; /* C'mon... */ return (SEM_ID)0; } } CANCEL_DEFER(svc); sem = alloc_sem(options, &msem_ops); if (sem == NULL) { errno = S_memLib_NOT_ENOUGH_MEMORY; CANCEL_RESTORE(svc); return (SEM_ID)0; } /* * XXX: POSIX-wise, we have a few issues with emulating * VxWorks semaphores of the mutex kind. * * VxWorks flushes any kind of semaphore upon deletion * (however, explicit semFlush() is not allowed on the mutex * kind though); but POSIX doesn't implement such mechanism on * its mutex object. At the same time, we need priority * inheritance when SEM_INVERSION_SAFE is passed, so we can't * emulate VxWorks mutex semaphores using condvars. Since the * only way to get priority inheritance is to use a POSIX * mutex, we choose not to emulate flushing in semDelete(), * but keep inversion-safe locking possible. * * The same way, we don't support FIFO ordering for mutexes, * since this would require to handle them as recursive binary * semaphores with ownership, for no obvious upside. * Logically speaking, relying on recursion without any * consideration for priority while serializing threads is * just asking for troubles anyway. */ pthread_mutexattr_init(&mattr); pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_RECURSIVE); /* pthread_mutexattr_setrobust_np() might not be implemented. */ pthread_mutexattr_setrobust_np(&mattr, PTHREAD_MUTEX_ROBUST_NP); if (options & SEM_INVERSION_SAFE) pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT); pthread_mutexattr_setpshared(&mattr, mutex_scope_attribute); __RT(pthread_mutex_init(&sem->u.msem.lock, &mattr)); pthread_mutexattr_destroy(&mattr); CANCEL_RESTORE(svc); return mainheap_ref(sem, SEM_ID); }
void *lm76Parse(void *param) { struct JsonNode *json = (struct JsonNode *)param; struct JsonNode *jsettings = NULL; struct JsonNode *jid = NULL; struct JsonNode *jchild = NULL; struct timeval tp; struct timespec ts; struct lm76data_t *lm76data = malloc(sizeof(struct lm76data_t)); int y = 0, interval = 10, rc = 0; int temp_corr = 0; char *stmp = NULL; int firstrun = 1; lm76data->nrid = 0; lm76data->id = NULL; lm76data->fd = 0; #ifndef __FreeBSD__ pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; #else pthread_mutex_t mutex; pthread_cond_t cond; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); #endif if((jid = json_find_member(json, "id"))) { jchild = json_first_child(jid); while(jchild) { if(json_find_string(jchild, "id", &stmp) == 0) { lm76data->id = realloc(lm76data->id, (sizeof(char *)*(size_t)(lm76data->nrid+1))); lm76data->id[lm76data->nrid] = malloc(strlen(stmp)+1); strcpy(lm76data->id[lm76data->nrid], stmp); lm76data->nrid++; } jchild = jchild->next; } } if((jsettings = json_find_member(json, "settings"))) { json_find_number(jsettings, "interval", &interval); json_find_number(jsettings, "temp-corr", &temp_corr); } json_delete(json); #ifndef __FreeBSD__ lm76data->fd = realloc(lm76data->fd, (sizeof(int)*(size_t)(lm76data->nrid+1))); for(y=0;y<lm76data->nrid;y++) { lm76data->fd[y] = wiringPiI2CSetup((int)strtol(lm76data->id[y], NULL, 16)); } #endif pthread_cleanup_push(lm76ParseCleanUp, (void *)lm76data); while(lm76_loop) { rc = gettimeofday(&tp, NULL); ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; if(firstrun) { ts.tv_sec += 1; firstrun = 0; } else { ts.tv_sec += interval; } pthread_mutex_lock(&mutex); rc = pthread_cond_timedwait(&cond, &mutex, &ts); if(rc == ETIMEDOUT) { #ifndef __FreeBSD__ for(y=0;y<lm76data->nrid;y++) { if(lm76data->fd[y] > 0) { int raw = wiringPiI2CReadReg16(lm76data->fd[y], 0x00); float temp = ((float)((raw&0x00ff)+((raw>>12)*0.0625))*1000); lm76->message = json_mkobject(); JsonNode *code = json_mkobject(); json_append_member(code, "id", json_mkstring(lm76data->id[y])); json_append_member(code, "temperature", json_mknumber((int)temp+temp_corr)); json_append_member(lm76->message, "code", code); json_append_member(lm76->message, "origin", json_mkstring("receiver")); json_append_member(lm76->message, "protocol", json_mkstring(lm76->id)); pilight.broadcast(lm76->id, lm76->message); json_delete(lm76->message); lm76->message = NULL; } else { logprintf(LOG_DEBUG, "error connecting to lm76"); logprintf(LOG_DEBUG, "(probably i2c bus error from wiringPiI2CSetup)"); logprintf(LOG_DEBUG, "(maybe wrong id? use i2cdetect to find out)"); sleep(1); } } #endif }
int pthread_spin_init (pthread_spinlock_t * lock, int pshared) { pthread_spinlock_t s; int cpus = 0; int result = 0; if (lock == NULL) { return EINVAL; } if (0 != ptw32_getprocessors (&cpus)) { cpus = 1; } if (cpus > 1) { if (pshared == PTHREAD_PROCESS_SHARED) { /* * Creating spinlock that can be shared between * processes. */ #if _POSIX_THREAD_PROCESS_SHARED >= 0 /* * Not implemented yet. */ #error ERROR [__FILE__, line __LINE__]: Process shared spin locks are not supported yet. #else return ENOSYS; #endif /* _POSIX_THREAD_PROCESS_SHARED */ } } s = (pthread_spinlock_t) calloc (1, sizeof (*s)); if (s == NULL) { return ENOMEM; } if (cpus > 1) { s->u.cpus = cpus; s->interlock = PTW32_SPIN_UNLOCKED; } else { pthread_mutexattr_t ma; result = pthread_mutexattr_init (&ma); if (0 == result) { ma->pshared = pshared; result = pthread_mutex_init (&(s->u.mutex), &ma); if (0 == result) { s->interlock = PTW32_SPIN_USE_MUTEX; } } (void) pthread_mutexattr_destroy (&ma); } if (0 == result) { *lock = s; } else { (void) free (s); *lock = NULL; } return (result); }
/** parent thread function **/ int main(void) { int ret; pthread_mutexattr_t ma; pthread_t th; output_init(); #if VERBOSE >1 output("Initialize the PTHREAD_MUTEX_RECURSIVE mutex\n"); #endif ret = pthread_mutexattr_init(&ma); if (ret != 0) { UNRESOLVED(ret, "Mutex attribute init failed"); } ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE); if (ret != 0) { UNRESOLVED(ret, "Set type recursive failed"); } ret = pthread_mutex_init(&m, &ma); if (ret != 0) { UNRESOLVED(ret, "Mutex init failed"); } #if VERBOSE >1 output("Lock the mutex\n"); #endif ret = pthread_mutex_lock(&m); if (ret != 0) { UNRESOLVED(ret, "Mutex lock failed"); } /* destroy the mutex attribute object */ ret = pthread_mutexattr_destroy(&ma); if (ret != 0) { UNRESOLVED(ret, "Mutex attribute destroy failed"); } #if VERBOSE >1 output("Create the thread\n"); #endif ret = pthread_create(&th, NULL, threaded, NULL); if (ret != 0) { UNRESOLVED(ret, "Thread creation failed"); } /* Let the thread terminate */ ret = pthread_join(th, NULL); if (ret != 0) { UNRESOLVED(ret, "Thread join failed"); } #if VERBOSE >1 output("Joined the thread\n"); #endif /* We can clean everything and exit */ ret = pthread_mutex_unlock(&m); if (ret != 0) { UNRESOLVED(ret, "Mutex unlock failed. Mutex got corrupted?"); } PASSED; }
static apr_status_t proc_mutex_proc_pthread_create(apr_proc_mutex_t *new_mutex, const char *fname) { apr_status_t rv; int fd; pthread_mutexattr_t mattr; fd = open("/dev/zero", O_RDWR); if (fd < 0) { return errno; } new_mutex->pthread_interproc = (pthread_mutex_t *)mmap( (caddr_t) 0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (new_mutex->pthread_interproc == (pthread_mutex_t *) (caddr_t) -1) { close(fd); return errno; } close(fd); new_mutex->curr_locked = -1; /* until the mutex has been created */ if ((rv = pthread_mutexattr_init(&mattr))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); return rv; } if ((rv = pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); pthread_mutexattr_destroy(&mattr); return rv; } #ifdef HAVE_PTHREAD_MUTEX_ROBUST if ((rv = pthread_mutexattr_setrobust_np(&mattr, PTHREAD_MUTEX_ROBUST_NP))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); pthread_mutexattr_destroy(&mattr); return rv; } if ((rv = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); pthread_mutexattr_destroy(&mattr); return rv; } #endif /* HAVE_PTHREAD_MUTEX_ROBUST */ if ((rv = pthread_mutex_init(new_mutex->pthread_interproc, &mattr))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); pthread_mutexattr_destroy(&mattr); return rv; } new_mutex->curr_locked = 0; /* mutex created now */ if ((rv = pthread_mutexattr_destroy(&mattr))) { #ifdef HAVE_ZOS_PTHREADS rv = errno; #endif proc_mutex_proc_pthread_cleanup(new_mutex); return rv; } apr_pool_cleanup_register(new_mutex->pool, (void *)new_mutex, apr_proc_mutex_cleanup, apr_pool_cleanup_null); return APR_SUCCESS; }
void init() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); assert(pthread_mutex_init(&native_, &attr) == 0); }
/* * The main thread must call this function to convert itself into a thread. */ thread_t * thread_initial (unsigned long stack_size) { int rc; thread_t *thr = NULL; if (_main_thread) return _main_thread; /* * Initialize pthread key */ #ifndef OLD_PTHREADS rc = pthread_key_create (&_key_current, NULL); #else rc = pthread_keycreate (&_key_current, NULL); #endif CKRET (rc); /* * Start off with a value of NULL */ rc = pthread_setspecific (_key_current, NULL); CKRET (rc); /* * Initialize default thread/mutex attributes */ #ifndef OLD_PTHREADS /* attribute for thread creation */ rc = pthread_attr_init (&_thread_attr); CKRET (rc); /* attribute for mutex creation */ rc = pthread_mutexattr_init (&_mutex_attr); CKRET (rc); #else rc = pthread_attr_create (&_thread_attr); CKRET (rc); rc = pthread_mutexattr_create (&_mutex_attr); CKRET (rc); #endif #if defined (PTHREAD_PROCESS_PRIVATE) && !defined(oldlinux) && !defined(__FreeBSD__) rc = pthread_mutexattr_setpshared (&_mutex_attr, PTHREAD_PROCESS_PRIVATE); CKRET (rc); #endif #if defined (MUTEX_FAST_NP) && !defined (_AIX) rc = pthread_mutexattr_setkind_np (&_mutex_attr, MUTEX_FAST_NP); CKRET (rc); #endif #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP rc = pthread_mutexattr_settype (&_mutex_attr, PTHREAD_MUTEX_ADAPTIVE_NP); CKRET (rc); #endif /* * Allocate a thread structure */ thr = (thread_t *) dk_alloc (sizeof (thread_t)); memset (thr, 0, sizeof (thread_t)); assert (_main_thread == NULL); _main_thread = thr; _sched_init (); if (stack_size == 0) stack_size = MAIN_STACK_SIZE; #if (SIZEOF_VOID_P == 8) stack_size *= 2; #endif #if defined (__x86_64 ) && defined (SOLARIS) /*GK: the LDAP on that platform requires that */ stack_size *= 2; #endif stack_size = ((stack_size / 8192) + 1) * 8192; thr->thr_stack_size = stack_size; thr->thr_status = RUNNING; thr->thr_cv = _alloc_cv (); thr->thr_sem = semaphore_allocate (0); thr->thr_schedule_sem = semaphore_allocate (0); if (thr->thr_cv == NULL) goto failed; _thread_init_attributes (thr); thread_set_priority (thr, NORMAL_PRIORITY); rc = pthread_setspecific (_key_current, thr); CKRET (rc); return thr; failed: if (thr) { _thread_free_attributes (thr); dk_free (thr, sizeof (thread_t)); } return NULL; }
/***** main program *****/ int main(int argc, char *argv[]) { pthread_mutex_t mtx_null, mtx_def; pthread_mutexattr_t mattr; pthread_t thr; pthread_mutex_t * tab_mutex[2]={&mtx_null, &mtx_def}; int tab_res[2][3]={{0,0,0},{0,0,0}}; int ret; void * th_ret; int i; output_init(); #if VERBOSE >1 output("Test starting...\n"); #endif /* We first initialize the two mutexes. */ if ((ret=pthread_mutex_init(&mtx_null, NULL))) { UNRESOLVED(ret, "NULL mutex init"); } if ((ret=pthread_mutexattr_init(&mattr))) { UNRESOLVED(ret, "Mutex attribute init"); } if ((ret=pthread_mutex_init(&mtx_def, &mattr))) { UNRESOLVED(ret, "Default attribute mutex init"); } if ((ret=pthread_mutexattr_destroy(&mattr))) { UNRESOLVED(ret, "Mutex attribute destroy"); } if ((ret=sem_init(&semA, 0, 0))) { UNRESOLVED(errno, "Sem A init"); } if ((ret=sem_init(&semB, 0, 0))) { UNRESOLVED(errno, "Sem B init"); } #if VERBOSE >1 output("Data initialized...\n"); #endif /* OK let's go for the first part of the test : abnormals unlocking */ /* We first check if unlocking an unlocked mutex returns an error. */ retval = pthread_mutex_unlock(tab_mutex[0]); ret = pthread_mutex_unlock(tab_mutex[1]); #if VERBOSE >0 output("Results for unlock issue #1:\n mutex 1 unlocking returned %i\n mutex 2 unlocking returned %i\n", retval, ret); #endif if (ret != retval) { FAILED("Unlocking an unlocked mutex behaves differently."); } /* Now we focus on unlocking a mutex lock by another thread */ for (i=0; i<2; i++) { p_mtx = tab_mutex[i]; tab_res[i][0]=0; tab_res[i][1]=0; tab_res[i][2]=0; #if VERBOSE >1 output("Creating thread (unlock)...\n"); #endif if ((ret = pthread_create(&thr, NULL, unlock_issue, NULL))) { UNRESOLVED(ret, "Unlock issue thread create"); } if ((ret = sem_wait(&semA))) { UNRESOLVED(errno, "Sem A wait failed for unlock issue."); } #if VERBOSE >1 output("Unlocking in parent...\n"); #endif retval = pthread_mutex_unlock(p_mtx); if ((ret = sem_post(&semB))) { UNRESOLVED(errno, "Sem B post failed for unlock issue."); } if ((ret=pthread_join(thr, &th_ret))) { UNRESOLVED(ret, "Join thread"); } #if VERBOSE >1 output("Thread joined successfully...\n"); #endif tab_res[i][0] = retval; } #if VERBOSE >0 output("Results for unlock issue #2:\n mutex 1 returned %i\n mutex 2 returned %i\n", tab_res[0][0],tab_res[1][0]); #endif if (tab_res[0][0] != tab_res[1][0]) { FAILED("Unlocking an unowned mutex behaves differently."); } /* We now are going to test the deadlock issue */ /* We start with testing the NULL mutex features */ for (i=0; i<2; i++) { p_mtx = tab_mutex[i]; tab_res[i][0]=0; tab_res[i][1]=0; tab_res[i][2]=0; #if VERBOSE >1 output("Creating thread (deadlk)...\n"); #endif if ((ret = pthread_create(&thr, NULL, deadlk_issue, NULL))) { UNRESOLVED(ret, "Deadlk_issue thread create"); } /* Now we are waiting the thread is ready to relock the mutex. */ if ((ret=sem_wait(&semA))) { UNRESOLVED(errno, "Sem wait"); } /* To ensure thread runs until second lock, we yield here */ sched_yield(); /* OK, now we cancel the thread */ canceled=0; #if VERBOSE >1 output("Cancel thread...\n"); #endif if (returned ==0) if ((ret=pthread_cancel(thr))) { UNRESOLVED(ret, "Cancel thread (deadlk_issue)"); } #if VERBOSE >1 output("Thread canceled...\n"); #endif if ((ret=pthread_join(thr, &th_ret))) { UNRESOLVED(ret, "Join thread"); } #if VERBOSE >1 output("Thread joined successfully...\n"); #endif tab_res[i][2] = retval; tab_res[i][1] = returned; tab_res[i][0] = canceled; } /* Now we parse the results */ #if VERBOSE >0 output("Results for deadlock issue:\n mutex 1 \t%s\t%s%i\n mutex 2 \t%s\t%s%i\n", tab_res[0][0]?"deadlock" : "no deadlock", tab_res[0][1]?"returned " : "did not return ", tab_res[0][2], tab_res[1][0]?"deadlock" : "no deadlock", tab_res[1][1]?"returned " : "did not return ", tab_res[1][2]); #endif if (tab_res[0][0] != tab_res[1][0]) { FAILED("One mutex deadlocks, not the other"); } if (tab_res[0][1] != tab_res[1][1]) { UNRESOLVED(tab_res[0][1], "Abnormal situation!"); } if ((tab_res[0][1] == 1) && (tab_res[0][2] != tab_res[1][2])) { FAILED("The locks returned different error codes."); } PASSED; }
// REMEMBER lock must contains space for both pthread_mutex_t and pthread_mutexattr_t !!! struct uwsgi_lock_item *uwsgi_lock_fast_init(char *id) { pthread_mutexattr_t attr; struct uwsgi_lock_item *uli = uwsgi_register_lock(id, 0); #ifdef EOWNERDEAD retry: #endif if (pthread_mutexattr_init(&attr)) { uwsgi_log("unable to allocate mutexattr structure\n"); exit(1); } if (pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)) { uwsgi_log("unable to share mutex\n"); exit(1); } #ifdef EOWNERDEAD #ifndef PTHREAD_MUTEX_ROBUST #define PTHREAD_MUTEX_ROBUST PTHREAD_MUTEX_ROBUST_NP #endif if (uwsgi_pthread_robust_mutexes_enabled) { if (pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT)) { uwsgi_log("unable to set PTHREAD_PRIO_INHERIT\n"); exit(1); } if (pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST)) { uwsgi_log("unable to make the mutex 'robust'\n"); exit(1); } } #endif if (pthread_mutex_init((pthread_mutex_t *) uli->lock_ptr, &attr)) { #ifdef EOWNERDEAD if (uwsgi_pthread_robust_mutexes_enabled) { uwsgi_log("!!! it looks like your kernel does not support pthread robust mutexes !!!\n"); uwsgi_log("!!! falling back to standard pthread mutexes !!!\n"); uwsgi_pthread_robust_mutexes_enabled = 0; pthread_mutexattr_destroy(&attr); goto retry; } #endif uwsgi_log("unable to initialize mutex\n"); exit(1); } pthread_mutexattr_destroy(&attr); #ifdef EOWNERDEAD if (!uwsgi_pthread_robust_mutexes_enabled) { uli->can_deadlock = 1; } #else uli->can_deadlock = 1; #endif return uli; }
/* Main entry point. */ int main(int argc, char * argv[]) { int ret; int sc; pthread_mutexattr_t ma; testdata_t * td; testdata_t alternativ; int do_fork; pid_t child_pr=0, chkpid; int status; pthread_t child_th; long pshared, mf; /* Initialize output */ output_init(); /* Test system abilities */ pshared = sysconf(_SC_THREAD_PROCESS_SHARED); mf =sysconf(_SC_MAPPED_FILES); #if VERBOSE > 0 output("Test starting\n"); output("System abilities:\n"); output(" TSH : %li\n", pshared); output(" MF : %li\n", mf); if ((mf < 0) || (pshared < 0)) output("Process-shared attributes won't be tested\n"); #endif #ifdef WITHOUT_XOPEN #if VERBOSE > 0 output("As XSI extension is disabled, we won't test the feature across process\n"); #endif mf = -1; #endif /********** * Allocate space for the testdata structure */ if (mf < 0) { /* Cannot mmap a file (or not interested in this), we use an alternative method */ td = &alternativ; pshared = -1; /* We won't do this testing anyway */ #if VERBOSE > 0 output("Testdata allocated in the process memory.\n"); #endif } #ifndef WITHOUT_XOPEN else { /* We will place the test data in a mmaped file */ char filename[] = "/tmp/mutex_trylock_1-2-XXXXXX"; size_t sz; void * mmaped; int fd; char * tmp; /* We now create the temp files */ fd = mkstemp(filename); if (fd == -1) { UNRESOLVED(errno, "Temporary file could not be created"); } /* and make sure the file will be deleted when closed */ unlink(filename); #if VERBOSE > 1 output("Temp file created (%s).\n", filename); #endif sz= (size_t)sysconf(_SC_PAGESIZE); tmp = calloc(1, sz); if (tmp == NULL) { UNRESOLVED(errno, "Memory allocation failed"); } /* Write the data to the file. */ if (write (fd, tmp, sz) != (ssize_t) sz) { UNRESOLVED(sz, "Writting to the file failed"); } free(tmp); /* Now we can map the file in memory */ mmaped = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (mmaped == MAP_FAILED) { UNRESOLVED(errno, "mmap failed"); } td = (testdata_t *) mmaped; /* Our datatest structure is now in shared memory */ #if VERBOSE > 1 output("Testdata allocated in shared memory.\n"); #endif } #endif /********** * For each test scenario, initialize the attributes and other variables. * Do the whole thing for each time to test. */ for (sc=0; sc < NSCENAR ; sc++) { #if VERBOSE > 1 output("[parent] Preparing attributes for: %s\n", scenarii[sc].descr); #endif /* set / reset everything */ do_fork=0; ret = pthread_mutexattr_init(&ma); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } #ifndef WITHOUT_XOPEN /* Set the mutex type */ ret = pthread_mutexattr_settype(&ma, scenarii[sc].m_type); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set mutex type"); } #if VERBOSE > 1 output("[parent] Mutex type : %i\n", scenarii[sc].m_type); #endif #endif /* Set the pshared attributes, if supported */ if ((pshared > 0) && (scenarii[sc].m_pshared != 0)) { ret = pthread_mutexattr_setpshared(&ma, PTHREAD_PROCESS_SHARED); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set the mutex process-shared"); } #if VERBOSE > 1 output("[parent] Mutex is process-shared\n"); #endif } #if VERBOSE > 1 else { output("[parent] Mutex is process-private\n"); } #endif /* Tell whether the test will be across processes */ if ((pshared > 0) && (scenarii[sc].fork != 0)) { do_fork = 1; #if VERBOSE > 1 output("[parent] Child will be a new process\n"); #endif } #if VERBOSE > 1 else { output("[parent] Child will be a new thread\n"); } #endif /********** * Initialize the testdata_t structure with the previously defined attributes */ /* Initialize the mutex */ ret = pthread_mutex_init(&(td->mtx), &ma); if (ret != 0) { UNRESOLVED(ret, "[parent] Mutex init failed"); } /* Initialize the other datas from the test structure */ td->status=0; /********** * Proceed to the actual testing */ /* Trylock the mutex twice before creating children */ ret = pthread_mutex_trylock(&(td->mtx)); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to trylock the mutex"); } ret = pthread_mutex_trylock(&(td->mtx)); #ifndef WITHOUT_XOPEN if (scenarii[sc].m_type == PTHREAD_MUTEX_RECURSIVE) { if (ret != 0) { UNRESOLVED(ret, "Failed to pthread_mutex_trylock() twice a recursive mutex"); } /* Unlock once so the count is "1" */ ret = pthread_mutex_unlock(&(td->mtx)); if (ret != 0) { UNRESOLVED(ret, "Failed to unlock the mutex"); } } else #endif if (ret == 0) { FAILED("Main was able to pthread_mutex_trylock() twice without error"); } /* Create the children */ if (do_fork != 0) { /* We are testing across processes */ child_pr = fork(); if (child_pr == -1) { UNRESOLVED(errno, "[parent] Fork failed"); } if (child_pr == 0) { #if VERBOSE > 3 output("[child] Child process is starting...\n"); #endif if (tf((void *)td) != NULL) { UNRESOLVED(-1, "[child] Got an unexpected return value from test function"); } else { /* We cannot use the PASSED macro here since it would terminate the output */ exit (0); } } /* Only the parent process goes further */ } else /* do_fork == 0 */ { /* We are testing across two threads */ ret = pthread_create(&child_th, NULL, tf, td); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to create the child thread."); } } /* Wait for the child to terminate */ if (do_fork != 0) { /* We were testing across processes */ ret = 0; chkpid = waitpid(child_pr, &status, 0); if (chkpid != child_pr) { output("Expected pid: %i. Got %i\n", (int)child_pr, (int)chkpid); UNRESOLVED(errno, "Waitpid failed"); } if (WIFSIGNALED(status)) { output("Child process killed with signal %d\n",WTERMSIG(status)); UNRESOLVED(-1 , "Child process was killed"); } if (WIFEXITED(status)) { ret = WEXITSTATUS(status); } else { UNRESOLVED(-1, "Child process was neither killed nor exited"); } if (ret != 0) { exit(ret); /* Output has already been closed in child */ } } else /* child was a thread */ { ret = pthread_join(child_th, NULL); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to join the thread"); } } /* Check the child status */ if (td->status != EBUSY) { output("Unexpected return value: %d (%s)\n", td->status, strerror(td->status)); FAILED("pthread_mutex_trylock() did not return EBUSY in the child"); } /* Unlock the mutex */ ret= pthread_mutex_unlock(&(td->mtx)); if (ret != 0) { UNRESOLVED(ret, "Failed to unlock the mutex"); } /********** * Destroy the data */ ret = pthread_mutex_destroy(&(td->mtx)); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the mutex"); } ret = pthread_mutexattr_destroy(&ma); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the mutex attribute object"); } } /* Proceed to the next scenario */ #if VERBOSE > 0 output("Test passed\n"); #endif PASSED; }
ReentrantLock::ReentrantLock() { pthread_mutexattr_init(&m_mutexAttr); pthread_mutexattr_settype(&m_mutexAttr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&m_mutex, &m_mutexAttr); }
int main (int argc, char * argv[]) { int ret; pthread_mutexattr_t ma; pthread_condattr_t ca; int scenar; pid_t p_child[NTHREADS]; pthread_t t_child[NTHREADS]; int ch; pid_t pid; int status; testdata_t alternativ; output_init(); /********** * Allocate space for the testdata structure */ /* Cannot mmap a file, we use an alternative method */ td = &alternativ; #if VERBOSE > 0 output("Testdata allocated in the process memory.\n"); #endif /* Do the test for each test scenario */ for (scenar=0; scenar < NSCENAR; scenar++) { /* set / reset everything */ ret = pthread_mutexattr_init(&ma); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } ret = pthread_condattr_init(&ca); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the cond attribute object"); } #ifndef WITHOUT_XOPEN /* Set the mutex type */ ret = pthread_mutexattr_settype(&ma, scenarii[scenar].m_type); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set mutex type"); } #endif /* Proceed to testing */ /* initialize the mutex */ ret = pthread_mutex_init(&td->mtx1, &ma); if (ret != 0) { UNRESOLVED(ret, "Mutex init failed"); } ret = pthread_mutex_init(&td->mtx2, &ma); if (ret != 0) { UNRESOLVED(ret, "Mutex init failed"); } ret = pthread_mutex_lock(&td->mtx2); if (ret != 0) { UNRESOLVED(ret, "Mutex lock failed"); } /* initialize the condvar */ ret = pthread_cond_init(&td->cnd, &ca); if (ret != 0) { UNRESOLVED(ret, "Cond init failed"); } #if VERBOSE > 2 output("[parent] Starting 1st pass of test %s\n", scenarii[scenar].descr); #endif td->count1=0; td->count2=0; td->predicate1=0; td->predicate2=0; /* Create all the children */ for (ch=0; ch < NTHREADS; ch++) { ret = pthread_create(&t_child[ch], NULL, child, NULL); if (ret != 0) { UNRESOLVED(ret, "Failed to create a child thread"); } } #if VERBOSE > 4 output("[parent] All children are running\n"); #endif /* Make sure all children are waiting */ ret = pthread_mutex_lock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to lock mutex", p_child); } ch = td->count1; while (ch < NTHREADS) { ret = pthread_mutex_unlock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } sched_yield(); ret = pthread_mutex_lock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to lock mutex",p_child); } ch = td->count1; } #if VERBOSE > 4 output("[parent] All children are waiting\n"); #endif /* Wakeup the children */ td->predicate1=1; ret = pthread_cond_broadcast(&td->cnd); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to signal the condition.", p_child); } ret = pthread_mutex_unlock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } /* Destroy the condvar (this must be safe) */ do { ret = pthread_cond_destroy(&td->cnd); usleep(10 * 1000); } while (ret == EBUSY); if (ret != 0) { FAILED_KILLALL("Unable to destroy the cond while no thread is blocked inside", p_child); } /* Reuse the cond memory */ memset(&td->cnd, 0xFF, sizeof(pthread_cond_t)); #if VERBOSE > 4 output("[parent] Condition was broadcasted, and condvar destroyed.\n"); #endif /* Make sure all children have exited the first wait */ ret = pthread_mutex_lock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to lock mutex",p_child); } ch = td->count1; while (ch > 0) { ret = pthread_mutex_unlock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } sched_yield(); ret = pthread_mutex_lock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to lock mutex",p_child); } ch = td->count1; } ret = pthread_mutex_unlock(&td->mtx1); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } /* Go toward the 2nd pass */ /* Now, all children are waiting to lock the 2nd mutex, which we own here. */ /* reinitialize the condvar */ ret = pthread_cond_init(&td->cnd, &ca); if (ret != 0) { UNRESOLVED(ret, "Cond init failed"); } #if VERBOSE > 2 output("[parent] Starting 2nd pass of test %s\n", scenarii[scenar].descr); #endif /* Make sure all children are waiting */ ch = td->count2; while (ch < NTHREADS) { ret = pthread_mutex_unlock(&td->mtx2); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } sched_yield(); ret = pthread_mutex_lock(&td->mtx2); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to lock mutex",p_child); } ch = td->count2; } #if VERBOSE > 4 output("[parent] All children are waiting\n"); #endif /* Wakeup the children */ td->predicate2=1; ret = pthread_cond_broadcast(&td->cnd); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to signal the condition.", p_child); } /* Allow the children to terminate */ ret = pthread_mutex_unlock(&td->mtx2); if (ret != 0) { UNRESOLVED_KILLALL(ret, "Failed to unlock mutex",p_child); } /* Destroy the condvar (this must be safe) */ ret = pthread_cond_destroy(&td->cnd); if (ret != 0) { FAILED_KILLALL("Unable to destroy the cond while no thread is blocked inside", p_child); } /* Reuse the cond memory */ memset(&td->cnd, 0x00, sizeof(pthread_cond_t)); #if VERBOSE > 4 output("[parent] Condition was broadcasted, and condvar destroyed.\n"); #endif #if VERBOSE > 4 output("[parent] Joining the children\n"); #endif /* join the children */ for (ch=(NTHREADS - 1); ch >= 0 ; ch--) { ret = pthread_join(t_child[ch], NULL); if (ret != 0) { UNRESOLVED(ret, "Failed to join a child thread"); } } if (ret != 0) { output_fini(); exit(ret); } #if VERBOSE > 4 output("[parent] All children terminated\n"); #endif /* Destroy the datas */ #if 0 // This seems wrong, as it was just destroyed and zeroed out above. ret = pthread_cond_destroy(&td->cnd); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the condvar"); } #endif ret = pthread_mutex_destroy(&td->mtx1); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the mutex"); } ret = pthread_mutex_destroy(&td->mtx2); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the mutex"); } /* Destroy the attributes */ ret = pthread_condattr_destroy(&ca); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the cond var attribute object"); } ret = pthread_mutexattr_destroy(&ma); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the mutex attribute object"); } } /* exit */ PASSED; return 0; }
/* Main function */ int main (int argc, char * argv[]) { int ret; int i; pthread_mutex_t mtx; pthread_mutexattr_t ma[NSCENAR + 1]; pthread_mutexattr_t *pma[NSCENAR + 2]; long pshared; /* Initialize output routine */ output_init(); /* System abilities */ pshared = sysconf(_SC_THREAD_PROCESS_SHARED); /* Initialize the mutex attributes objects */ for (i=0; i<NSCENAR; i++) { ret = pthread_mutexattr_init(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } /* Set the mutex type */ ret = pthread_mutexattr_settype(&ma[i], scenarii[i].m_type); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set mutex type"); } /* Set the pshared attributes, if supported */ if ((pshared > 0) && (scenarii[i].m_pshared != 0)) { ret = pthread_mutexattr_setpshared(&ma[i], PTHREAD_PROCESS_SHARED); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to set the mutex process-shared"); } } } /* Default mutexattr object */ ret = pthread_mutexattr_init(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "[parent] Unable to initialize the mutex attribute object"); } /* Initialize the pointer array */ for (i=0; i<NSCENAR+1; i++) pma[i]=&ma[i]; /* NULL pointer */ pma[i] = NULL; /* Ok, we can now proceed to the test */ #if VERBOSE > 0 output("Attributes are ready, proceed to the test\n"); #endif for (i=0; i<NSCENAR + 2; i++) { #if VERBOSE > 1 char * nul="NULL"; char * def ="Default"; char * stri; if (i<NSCENAR) stri = scenarii[i].descr; if (i==NSCENAR) stri = def; if (i==NSCENAR+1) stri = nul; output("Init with: %s\n", stri); #endif ret = pthread_mutex_init(&mtx, pma[i]); if (ret != 0) { UNRESOLVED(ret, "Failed to init the mutex"); } ret = pthread_mutex_lock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to lock the mutex"); } ret = pthread_mutex_unlock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to unlcok the mutex"); } ret = pthread_mutex_destroy(&mtx); if (ret != 0) { FAILED("Failed to destroy an initialized unlocked mutex"); } } #if VERBOSE > 0 output("Test passed; destroying the test data\n"); #endif for (i=0; i<NSCENAR + 1; i++) { ret = pthread_mutexattr_destroy(&ma[i]); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy a mutex attribute object"); } } PASSED; }