Search Results

Search found 166 results on 7 pages for 'pthreads'.

Page 2/7 | < Previous Page | 1 2 3 4 5 6 7  | Next Page >

  • GCC - How to realign stack?

    - by psihodelia
    I try to build an application which uses pthreads and __m128 SSE type. According to GCC manual, default stack alignment is 16 bytes. In order to use __m128, the requirement is the 16-byte alignment. My target CPU supports SSE. I use a GCC compiler which doesn't support runtime stack realignment (e.g. -mstackrealign). I cannot use any other GCC compiler version. My test application looks like: #include <xmmintrin.h> #include <pthread.h> void *f(void *x){ __m128 y; ... } int main(void){ pthread_t p; pthread_create(&p, NULL, f, NULL); } The application generates an exception and exits. After a simple debugging (printf "%p", &y), I found that the variable y is not 16-byte aligned. My question is: how can I realign the stack properly (16-byte) without using any GCC flags and attributes (they don't help)? Should I use GCC inline Assembler within this thread function f()?

    Read the article

  • gdb: Cannot find new threads: generic error

    - by Alexander Gladysh
    When I run GDB against a program which loads a .so which is linked to pthreads, GDB reports error "Cannot find new threads: generic error". I probably miss something in my Ubuntu configuration (as it was installed from minimal install). Any clues? $ gdb --args lua -lluarocks.require GNU gdb (GDB) 7.0-ubuntu Copyright (C) 2009 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /usr/bin/lua...(no debugging symbols found)...done. (gdb) run Starting program: /usr/bin/lua -lluarocks.require Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio require 'ev' [Thread debugging using libthread_db enabled] Cannot find new threads: generic error (gdb) q A debugging session is active. Inferior 1 [process 4986] will be killed. Quit anyway? (y or n) y This function gets called on require 'ev': http://github.com/brimworks/lua-ev/blob/master/lua_ev.c#L25-65 Additional information about my system: $ uname -a Linux localhost 2.6.31-20-generic #58-Ubuntu SMP Fri Mar 12 04:38:19 UTC 2010 x86_64 GNU/Linux $ lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 9.10 Release: 9.10 Codename: karmic

    Read the article

  • How to properly handle signals when using the worker thread pattern?

    - by ipartola
    I have a simple server that looks something like this: void *run_thread(void *arg) { // Communicate via a blocking socket } int main() { // Initialization happens here... // Main event loop while (1) { new_client = accept(socket, ...); pthread_create(&thread, NULL, &run_thread, *thread_data*); pthread_detach(thread); } // Do cleanup stuff: close(socket); // Wait for existing threads to finish exit(0); ) Thus when a SIGINT or SIGTERM is received I need to break out of the main event loop to get to the clean up code. Moreover most likely the master thread is waiting on the accept() call so it's not able to check some other variable to see if it should break;. Most of the advice I found was along the lines of this: http://devcry.blogspot.com/2009/05/pthreads-and-unix-signals.html (creating a special signal handling thread to catch all the signals and do processing on those). However, it's the processing portion that I can't really wrap my head around: how can I possibly tell the main thread to return from the accept() call and check on an external variable to see if it should break;?

    Read the article

  • how to emulate thread local storage at user space in C++ ?

    - by vprajan
    I am working on a mobile platform over Nucleus RTOS. It uses Nucleus Threading system but it doesn't have support for explicit thread local storage i.e, TlsAlloc, TlsSetValue, TlsGetValue, TlsFree APIs. The platform doesn't have user space pthreads as well. I found that __thread storage modifier is present in most of the C++ compilers. But i don't know how to make it work for my kind of usage. How does __thread keyword can be mapped with explicit thread local storage? I read many articles but nothing is so clear for giving me the following basic information will __thread variable different for each thread ? How to write to that and read from it ? does each thread has exactly one copy of the variable ? following is the pthread based implementation: pthread_key_t m_key; struct Data : Noncopyable { Data(T* value, void* owner) : value(value), owner(owner) {} int* value; }; inline ThreadSpecific() { int error = pthread_key_create(&m_key, destroy); if (error) CRASH(); } inline ~ThreadSpecific() { pthread_key_delete(m_key); // Does not invoke destructor functions. } inline T* get() { Data* data = static_cast<Data*>(pthread_getspecific(m_key)); return data ? data->value : 0; } inline void set(T* ptr) { ASSERT(!get()); pthread_setspecific(m_key, new Data(ptr, this)); } How to make the above code use __thread way to set & get specific value ? where/when does the create & delete happen? If this is not possible, how to write custom pthread_setspecific, pthread_getspecific kind of APIs. I tried using a C++ global map and index it uniquely for each thread and retrieved data from it. But it didn't work well.

    Read the article

  • pthreads_setaffinity_np: Invalid argument?

    - by hahuang65
    I've managed to get my pthreads program sort of working. Basically I am trying to manually set the affinity of 4 threads such that thread 1 runs on CPU 1, thread 2 runs on CPU 2, thread 3 runs on CPU 3, and thread 4 runs on CPU 4. After compiling, my code works for a few threads but not others (seems like thread 1 never works) but running the same compiled program a couple of different times gives me different results. For example: hao@Gorax:~/Desktop$ ./a.out Thread 3 is running on CPU 3 pthread_setaffinity_np: Invalid argument Thread Thread 2 is running on CPU 2 hao@Gorax:~/Desktop$ ./a.out Thread 2 is running on CPU 2 pthread_setaffinity_np: Invalid argument pthread_setaffinity_np: Invalid argument Thread 3 is running on CPU 3 Thread 3 is running on CPU 3 hao@Gorax:~/Desktop$ ./a.out Thread 2 is running on CPU 2 pthread_setaffinity_np: Invalid argument Thread 4 is running on CPU 4 Thread 4 is running on CPU 4 hao@Gorax:~/Desktop$ ./a.out pthread_setaffinity_np: Invalid argument My question is "Why does this happen? Also, why does the message sometimes print twice?" Here is the code: #define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <sched.h> #include <errno.h> #define handle_error_en(en, msg) \ do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0) void *thread_function(char *message) { int s, j, number; pthread_t thread; cpu_set_t cpuset; number = (int)message; thread = pthread_self(); CPU_SET(number, &cpuset); s = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset); if (s != 0) { handle_error_en(s, "pthread_setaffinity_np"); } printf("Thread %d is running on CPU %d\n", number, sched_getcpu()); exit(EXIT_SUCCESS); } int main() { pthread_t thread1, thread2, thread3, thread4; int thread1Num = 1; int thread2Num = 2; int thread3Num = 3; int thread4Num = 4; int thread1Create, thread2Create, thread3Create, thread4Create, i, temp; thread1Create = pthread_create(&thread1, NULL, (void *)thread_function, (char *)thread1Num); thread2Create = pthread_create(&thread2, NULL, (void *)thread_function, (char *)thread2Num); thread3Create = pthread_create(&thread3, NULL, (void *)thread_function, (char *)thread3Num); thread4Create = pthread_create(&thread4, NULL, (void *)thread_function, (char *)thread4Num); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); return 0; }

    Read the article

  • Multiplying matrices: error: expected primary-expression before 'struct'

    - by justin
    I am trying to write a program that is supposed to multiply matrices using threads. I am supposed to fill the matrices using random numbers in a thread. I am compiling in g++ and using PTHREADS. I have also created a struct to pass the data from my command line input to the thread so it can generate the matrix of random numbers. The sizes of the two matrices are also passed in the command line as well. I keep getting: main.cpp:7: error: expected primary-expression before 'struct' my code @ line 7 =: struct a{ int Arow; int Acol; int low; int high; }; My inpust are : Sizes of two matrices ( 4 arguments) high and low ranges in which o generate the random numbers between. Complete code: [headers] using namespace std; void *matrixACreate(struct *); void *status; int main(int argc, char * argv[]) { int Arow = atoi(argv[1]); // Matrix A int Acol = atoi(argv[2]); // WxX int Brow = atoi(argv[3]); // Matrix B int Bcol = atoi(argv[4]); // XxZ, int low = atoi(argv[5]); // Range low int high = atoi(argv[6]); struct a{ int Arow; // Matrix A int Acol; // WxX int low; // Range low int high; }; pthread_t matrixAthread; //pthread_t matrixBthread; pthread_t runner; int error, retValue; if (Acol != Brow) { cout << " This matrix cannot be multiplied. FAIL" << endl; return 0; } error = pthread_create(&matrixAthread, NULL, matrixACreate, struct *a); //error = pthread_create(&matrixAthread, NULL, matrixBCreate, sendB); retValue = pthread_join(matrixAthread, &status); //retValue = pthread_join(matrixBthread, &status); return 0; } void matrixACreate(struct * a) { struct a *data = (struct a *) malloc(sizeof(struct a)); data->Arow = Arow; data->Acol = Acol; data->low = low; data->high = high; int range = ((high - low) + 1); cout << Arow << endl<< Acol << endl; }// just trying to print to see if I am in the thread

    Read the article

  • sigwait in Linux (Fedora 13) vs OS X

    - by Silas
    So I'm trying to create a signal handler using pthreads which works on both OS X and Linux. The code below works on OS X but doesn't work on Fedora 13. The application is fairly simple. It spawns a pthread, registers SIGHUP and waits for a signal. After spawning the signal handler I block SIGHUP in the main thread so the signal should only be sent to the signal_handler thread. On OS X this works fine, if I compile, run and send SIGHUP to the process it prints "Got SIGHUP". On Linux it just kills the process (and prints Hangup). If I comment out the signal_handler pthread_create the application doesn't die. I know the application gets to the sigwait and blocks but instead of return the signal code it just kills the application. I ran the test using the following commands: g++ test.cc -lpthread -o test ./test & PID="$!" sleep 1 kill -1 "$PID" test.cc #include <pthread.h> #include <signal.h> #include <iostream> using namespace std; void *signal_handler(void *arg) { int sig; sigset_t set; sigemptyset(&set); sigaddset(&set, SIGHUP); while (true) { cout << "Wait for signal" << endl; sigwait(&set, &sig); if (sig == SIGHUP) { cout << "Got SIGHUP" << endl; } } } int main() { pthread_t handler; sigset_t set; // Create signal handler pthread_create(&handler, NULL, signal_handler, NULL); // Ignore SIGHUP in main thread sigfillset(&set); sigaddset(&set, SIGHUP); pthread_sigmask(SIG_BLOCK, &set, NULL); for (int i = 1; i < 5; i++) { cout << "Sleeping..." << endl; sleep(1); } pthread_join(handler, NULL); return 0; }

    Read the article

  • how to clear stack after stack overflow signal occur

    - by user353573
    In pthread, After reaching yellow zone in stack, signal handler stop the recursive function by making it return however, we can only continue to use extra area in yellow zone, how to clear the rubbish before the yellow zone in the thread stack ? (Copied from "answers"): #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <setjmp.h> #include <sys/mman.h> #include <unistd.h> #include <assert.h> #include <sys/resource.h> #define ALT_STACK_SIZE (64*1024) #define YELLOW_ZONE_PAGES (1) typedef struct { size_t stack_size; char* stack_pointer; char* red_zone_boundary; char* yellow_zone_boundary; sigjmp_buf return_point; size_t red_zone_size; } ThreadInfo; static pthread_key_t thread_info_key; static struct sigaction newAct, oldAct; bool gofromyellow = false; int call_times = 0; static void main_routine(){ // make it overflow if(gofromyellow == true) { printf("return from yellow zone, called %d times\n", call_times); return; } else { call_times = call_times + 1; main_routine(); gofromyellow = true; } } // red zone management static void stackoverflow_routine(){ fprintf(stderr, "stack overflow error.\n"); fflush(stderr); } // yellow zone management static void yellow_zone_hook(){ fprintf(stderr, "exceed yellow zone.\n"); fflush(stderr); } static int get_stack_info(void** stackaddr, size_t* stacksize){ int ret = -1; pthread_attr_t attr; pthread_attr_init(&attr); if(pthread_getattr_np(pthread_self(), &attr) == 0){ ret = pthread_attr_getstack(&attr, stackaddr, stacksize); } pthread_attr_destroy(&attr); return ret; } static int is_in_stack(const ThreadInfo* tinfo, char* pointer){ return (tinfo->stack_pointer <= pointer) && (pointer < tinfo->stack_pointer + tinfo->stack_size); } static int is_in_red_zone(const ThreadInfo* tinfo, char* pointer){ if(tinfo->red_zone_boundary){ return (tinfo->stack_pointer <= pointer) && (pointer < tinfo->red_zone_boundary); } } static int is_in_yellow_zone(const ThreadInfo* tinfo, char* pointer){ if(tinfo->yellow_zone_boundary){ return (tinfo->red_zone_boundary <= pointer) && (pointer < tinfo->yellow_zone_boundary); } } static void set_yellow_zone(ThreadInfo* tinfo){ int pagesize = sysconf(_SC_PAGE_SIZE); assert(pagesize > 0); tinfo->yellow_zone_boundary = tinfo->red_zone_boundary + pagesize * YELLOW_ZONE_PAGES; mprotect(tinfo->red_zone_boundary, pagesize * YELLOW_ZONE_PAGES, PROT_NONE); } static void reset_yellow_zone(ThreadInfo* tinfo){ size_t pagesize = tinfo->yellow_zone_boundary - tinfo->red_zone_boundary; if(mmap(tinfo->red_zone_boundary, pagesize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0) == 0){ perror("mmap failed"), exit(1); } mprotect(tinfo->red_zone_boundary, pagesize, PROT_READ | PROT_WRITE); tinfo->yellow_zone_boundary = 0; } static void signal_handler(int sig, siginfo_t* sig_info, void* sig_data){ if(sig == SIGSEGV){ ThreadInfo* tinfo = (ThreadInfo*) pthread_getspecific(thread_info_key); char* fault_address = (char*) sig_info->si_addr; if(is_in_stack(tinfo, fault_address)){ if(is_in_red_zone(tinfo, fault_address)){ siglongjmp(tinfo->return_point, 1); }else if(is_in_yellow_zone(tinfo, fault_address)){ reset_yellow_zone(tinfo); yellow_zone_hook(); gofromyellow = true; return; } else { //inside stack not related overflow SEGV happen } } } } static void register_application_info(){ pthread_key_create(&thread_info_key, NULL); sigemptyset(&newAct.sa_mask); sigaddset(&newAct.sa_mask, SIGSEGV); newAct.sa_sigaction = signal_handler; newAct.sa_flags = SA_SIGINFO | SA_RESTART | SA_ONSTACK; sigaction(SIGSEGV, &newAct, &oldAct); } static void register_thread_info(ThreadInfo* tinfo){ stack_t ss; pthread_setspecific(thread_info_key, tinfo); get_stack_info((void**)&tinfo->stack_pointer, &tinfo->stack_size); printf("stack size %d mb\n", tinfo->stack_size/1024/1024 ); tinfo->red_zone_boundary = tinfo->stack_pointer + tinfo->red_zone_size; set_yellow_zone(tinfo); ss.ss_sp = (char*)malloc(ALT_STACK_SIZE); ss.ss_size = ALT_STACK_SIZE; ss.ss_flags = 0; sigaltstack(&ss, NULL); } static void* thread_routine(void* p){ ThreadInfo* tinfo = (ThreadInfo*)p; register_thread_info(tinfo); if(sigsetjmp(tinfo->return_point, 1) == 0){ main_routine(); } else { stackoverflow_routine(); } free(tinfo); printf("after tinfo, end thread\n"); return 0; } int main(int argc, char** argv){ register_application_info(); if( argc == 2 ){ int stacksize = atoi(argv[1]); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 1024 * 1024 * stacksize); { pthread_t pid0; ThreadInfo* tinfo = (ThreadInfo*)calloc(1, sizeof(ThreadInfo)); pthread_attr_getguardsize(&attr, &tinfo->red_zone_size); pthread_create(&pid0, &attr, thread_routine, tinfo); pthread_join(pid0, NULL); } } else { printf("Usage: %s stacksize(mb)\n", argv[0]); } return 0; } C language in linux, ubuntu

    Read the article

  • How to use c++0x thread in Android NDK?

    - by m-ric
    I am trying to compile this simple program with android-ndk-r8b: jni/hello_jni.cpp #include <iostream> #include <thread> void hello() { std::cout << "Hi i'm a thread!!!" << std::endl; } int main() { std::thread th(hello); th.join(); return 0; } jni/Application.mk APP_OPTIM := release APP_MODULES := hello_thread APP_STL := gnustl_static jni/Android.mk LOCAL_PATH := $(call my-dir) include $(CLEAR_VARS) LOCAL_CPPFLAGS += -std=c++0x -frtti LOCAL_MODULE := hello_thread LOCAL_LDLIBS := -L$(SYSROOT)/usr/lib -pthread LOCAL_SRC_FILES := hello_thread.cpp include $(BUILD_EXECUTABLE) ndk-build returns me an error arguin that 'thread' is not a member of 'std'. I issued ndk-build -n to get the compilation command and issued it alone in my shell: /home/evigier/android-ndk-r8b/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86/bin/arm-linux-androideabi-g++ -MMD -MP -MF /home/evigier/eclipse_workspace/hello_thread/obj/local/armeabi/objs/hello_thread/hello_thread.o.d -fpic -ffunction-sections -funwind-tables -fstack-protector -D__ARM_ARCH_5__ -D__ARM_ARCH_5T__ -D__ARM_ARCH_5E__ -D__ARM_ARCH_5TE__ -march=armv5te -mtune=xscale -msoft-float -fno-exceptions -fno-rtti -mthumb -Os -fomit-frame-pointer -fno-strict-aliasing -finline-limit=64 -I/home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include -I/home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/libs/armeabi/include -I/home/evigier/eclipse_workspace/hello_thread/jni -DANDROID -Wa,--noexecstack -std=c++0x -frtti -O2 -DNDEBUG -g -I/home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include -c /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp -o /home/evigier/eclipse_workspace/hello_thread/obj/local/armeabi/objs/hello_thread/hello_thread.o Compile++ thumb : hello_thread <= hello_thread.cpp In file included from /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/stdio.h:55:0, from /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/wchar.h:33, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/cwchar:46, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/bits/postypes.h:42, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/iosfwd:42, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/ios:39, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/ostream:40, from /home/evigier/android-ndk-r8b/sources/cxx-stl/gnu-libstdc++/4.6/include/iostream:40, from jni/hello_thread.cpp:4: /home/evigier/android-ndk-r8b/platforms/android-14/arch-arm/usr/include/sys/types.h:124:9: error: 'uint64_t' does not name a type /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp: In function 'int main()': /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:14:5: error: 'thread' is not a member of 'std' /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:14:17: error: expected ';' before 'th' /home/evigier/eclipse_workspace/hello_thread/jni/hello_thread.cpp:15:5: error: 'th' was not declared in this scope I read a lot of threads/questions about POSIX threads and C++ threads, but still cannot find my answer. My arm-linux-androideabi/include/c++/4.6/thread file defines class thread in std only: #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) They don't seem to be defined in my sdk (c++config.h). But how can I possibly turn them on safely? Do i need to compile my own toolchain to use (non-p)threads? My host computer is : Linux evigier-ThinkPad-X220 3.0.0-17-generic #30-Ubuntu SMP Thu Mar 8 20:45:39 UTC 2012 x86_64 x86_64 x86_64 GNU/Linux

    Read the article

  • NPTL Default Stack Size Problem

    - by eyazici
    Hello, I am developing a multithread modular application using C programming language and NPTL 2.6. For each plugin, a POSIX thread is created. The problem is each thread has its own stack area, since default stack size depends on user's choice, this may results in huge memory consumption in some cases. To prevent unnecessary memory usage I used something similar to this to change stack size before creating each thread: pthread_attr_t attr; pthread_attr_init (&attr); pthread_attr_getstacksize(&attr, &st1); if(pthread_attr_setstacksize (&attr, MODULE_THREAD_SIZE) != 0) perror("Stack ERR"); pthread_attr_getstacksize(&attr, &st2); printf("OLD:%d, NEW:%d - MIN: %d\n", st1, st2, PTHREAD_STACK_MIN); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); /* "this" is static data structure that stores plugin related data */ pthread_create(&this->runner, &attr, (void *)(void *)this->run, NULL); EDIT I: pthread_create() section added. This did not work work as I expected, the stack size reported by pthread_attr_getstacksize() is changed but total memory usage of the application (from ps/top/pmap output) did not changed: OLD:10485760, NEW:65536 - MIN: 16384 When I use ulimit -s MY_STACK_SIZE_LIMIT before starting application I achieve the expected result. My questions are: 1-) Is there any portable(between UNIX variants) way to change (default)thread stack size after starting application(before creating thread of course)? 2-) Is it possible to use same stack area for every thread? 3-) Is it possible completely disable stack for threads without much pain?

    Read the article

  • How to use pthread_atfork() and pthread_once() to reinitialize mutexes in child processes

    - by Blair Zajac
    We have a C++ shared library that uses ZeroC's Ice library for RPC and unless we shut down Ice's runtime, we've observed child processes hanging on random mutexes. The Ice runtime starts threads, has many internal mutexes and keeps open file descriptors to servers. Additionally, we have a few of mutexes of our own to protect our internal state. Our shared library is used by hundreds of internal applications so we don't have control over when the process calls fork(), so we need a way to safely shutdown Ice and lock our mutexes while the process forks. Reading the POSIX standard on pthread_atfork() on handling mutexes and internal state: Alternatively, some libraries might have been able to supply just a child routine that reinitializes the mutexes in the library and all associated states to some known value (for example, what it was when the image was originally executed). This approach is not possible, though, because implementations are allowed to fail *_init() and *_destroy() calls for mutexes and locks if the mutex or lock is still locked. In this case, the child routine is not able to reinitialize the mutexes and locks. On Linux, the this test C program returns EPERM from pthread_mutex_unlock() in the child pthread_atfork() handler. Linux requires adding _NP to the PTHREAD_MUTEX_ERRORCHECK macro for it to compile. This program is linked from this good thread. Given that it's technically not safe or legal to unlock or destroy a mutex in the child, I'm thinking it's better to have pointers to mutexes and then have the child make new pthread_mutex_t on the heap and leave the parent's mutexes alone, thereby having a small memory leak. The only issue is how to reinitialize the state of the library and I'm thinking of reseting a pthread_once_t. Maybe because POSIX has an initializer for pthread_once_t that it can be reset to its initial state. #include <pthread.h> #include <stdlib.h> #include <string.h> static pthread_once_t once_control = PTHREAD_ONCE_INIT; static pthread_mutex_t *mutex_ptr = 0; static void setup_new_mutex() { mutex_ptr = malloc(sizeof(*mutex_ptr)); pthread_mutex_init(mutex_ptr, 0); } static void prepare() { pthread_mutex_lock(mutex_ptr); } static void parent() { pthread_mutex_unlock(mutex_ptr); } static void child() { // Reset the once control. pthread_once_t once = PTHREAD_ONCE_INIT; memcpy(&once_control, &once, sizeof(once_control)); setup_new_mutex(); } static void init() { setup_new_mutex(); pthread_atfork(&prepare, &parent, &child); } int my_library_call(int arg) { pthread_once(&once_control, &init); pthread_mutex_lock(mutex_ptr); // Do something here that requires the lock. int result = 2*arg; pthread_mutex_unlock(mutex_ptr); return result; } In the above sample in the child() I only reset the pthread_once_t by making a copy of a fresh pthread_once_t initialized with PTHREAD_ONCE_INIT. A new pthread_mutex_t is only created when the library function is invoked in the child process. This is hacky but maybe the best way of dealing with this skirting the standards. If the pthread_once_t contains a mutex then the system must have a way of initializing it from its PTHREAD_ONCE_INIT state. If it contains a pointer to a mutex allocated on the heap than it'll be forced to allocate a new one and set the address in the pthread_once_t. I'm hoping it doesn't use the address of the pthread_once_t for anything special which would defeat this. Searching comp.programming.threads group for pthread_atfork() shows a lot of good discussion and how little the POSIX standards really provides to solve this problem. There's also the issue that one should only call async-signal-safe functions from pthread_atfork() handlers, and it appears the most important one is the child handler, where only a memcpy() is done. Does this work? Is there a better way of dealing with the requirements of our shared library?

    Read the article

  • linux pthread_suspend

    - by johnnycrash
    Looks like linux doesnt implement pthread_suspend and continue, but I really need em. I have tried cond_wait, but it is too slow. The work being threaded mostly executes in 50us but occasionally executes upwards of 500ms. The problem with cond_wait is two-fold. The mutex locking is taking comparable times to the micro second executions and I don't need locking. Second, I have many worker threads and I don't really want to make N condition variables when they need to be woken up. I know exactly which thread is waiting for which work and could just pthread_continue that thread. A thread knows when there is no more work and can easily pthread_suspend itself. This would use no locking, avoid the stampede, and be faster. Problem is....no pthread_suspend or _continue. Any ideas?

    Read the article

  • gdb : multithreading

    - by Arpit
    Hi Wish to know that I have a program which uses two threads I have put the break point in both the threads. While running the program under gdb I want to switch between the threads and make them run. (thread t1 is active and running and thread t2 hold on the breakpoint I want to stop T1 running and run the T2) Is there any way that I can schedule the threads in gdb. Thanks Arpit

    Read the article

  • pthread windows event equivalent question

    - by ScaryAardvark
    I have the following code which replicates the windows manual and auto reset events. class event { public: event( bool signalled = false, bool ar = true ) : _auto( ar ), _signalled( signalled ) { pthread_mutex_init( &_mutex, NULL ); pthread_cond_init( &_cond, NULL ); } ~event() { pthread_cond_destroy( &_cond ); pthread_mutex_destroy( &_mutex ); } void set() { pthread_mutex_lock( &_mutex ); // only set and signal if we are unset if ( _signalled == false ) { _signalled = true; pthread_cond_signal( &_cond ); } pthread_mutex_unlock( &_mutex ); } void wait() { pthread_mutex_lock( &_mutex ); while ( _signalled == false ) { pthread_cond_wait( &_cond, &_mutex ); } // if we're an autoreset event, auto reset if ( _auto ) { _signalled = false; } pthread_mutex_unlock( &_mutex ); } void reset() { pthread_mutex_lock( &_mutex ); _signalled = false; pthread_mutex_unlock( &_mutex ); } private: pthread_mutex_t _mutex; pthread_cond_t _cond; bool _signalled; bool _auto; }; My question surrounds the "optimisation" I've put in place in the set() method where I only call pthread_cond_signal() if the event was unsignalled. Is this a valid optimisation or have I introduced some subtle flaw by doing so.

    Read the article

  • POSIX threads and signals

    - by Donal Fellows
    I've been trying to understand the intricacies of how POSIX threads and POSIX signals interact. In particular, I'm interested in: What's the best way to control which thread a signal is delivered to (assuming it isn't fatal in the first place)? What is the best way to tell another thread (that might actually be busy) that the signal has arrived? (I already know that it's a bad idea to be using pthread condition variables from a signal handler.) For reference about why I want this, I'm researching how to convert the TclX package to support threads, or to split it up and at least make some useful parts support threads. Signals are one of those parts that is of particular interest.

    Read the article

  • ubuntu: sem_timedwait not waking (C)

    - by gillez
    I have 3 processes which need to be synchronized. Process one does something then wakes process two and sleeps, which does something then wakes process three and sleeps, which does something and wakes process one and sleeps. The whole loop is timed to run around 25hz (caused by an external sync into process one before it triggers process two in my "real" application). I use sem_post to trigger (wake) each process, and sem_timedwait() to wait for the trigger. This all works successfully for several hours. However at some random time (usually after somewhere between two and four hours), one of the processes starts timing out in sem_timedwait(), even though I am sure the semaphore is being triggered with sem_post(). To prove this I even use sem_getvalue() immediately after the timeout, and the value is 1, so the timedwait should have been triggered. Please see following code: #include <stdio.h> #include <time.h> #include <string.h> #include <errno.h> #include <semaphore.h> sem_t trigger_sem1, trigger_sem2, trigger_sem3; // The main thread process. Called three times with a different num arg - 1, 2 or 3. void *thread(void *arg) { int num = (int) arg; sem_t *wait, *trigger; int val, retval; struct timespec ts; struct timeval tv; switch (num) { case 1: wait = &trigger_sem1; trigger = &trigger_sem2; break; case 2: wait = &trigger_sem2; trigger = &trigger_sem3; break; case 3: wait = &trigger_sem3; trigger = &trigger_sem1; break; } while (1) { // The first thread delays by 40ms to time the whole loop. // This is an external sync in the real app. if (num == 1) usleep(40000); // print sem value before we wait. If this is 1, sem_timedwait() will // return immediately, otherwise it will block until sem_post() is called on this sem. sem_getvalue(wait, &val); printf("sem%d wait sync sem%d. val before %d\n", num, num, val); // get current time and add half a second for timeout. gettimeofday(&tv, NULL); ts.tv_sec = tv.tv_sec; ts.tv_nsec = (tv.tv_usec + 500000); // add half a second if (ts.tv_nsec > 1000000) { ts.tv_sec++; ts.tv_nsec -= 1000000; } ts.tv_nsec *= 1000; /* convert to nanosecs */ retval = sem_timedwait(wait, &ts); if (retval == -1) { // timed out. Print value of sem now. This should be 0, otherwise sem_timedwait // would have woken before timeout (unless the sem_post happened between the // timeout and this call to sem_getvalue). sem_getvalue(wait, &val); printf("!!!!!! sem%d sem_timedwait failed: %s, val now %d\n", num, strerror(errno), val); } else printf("sem%d wakeup.\n", num); // get value of semaphore to trigger. If it's 1, don't post as it has already been // triggered and sem_timedwait on this sem *should* not block. sem_getvalue(trigger, &val); if (val <= 0) { printf("sem%d send sync sem%d. val before %d\n", num, (num == 3 ? 1 : num+1), val); sem_post(trigger); } else printf("!! sem%d not sending sync, val %d\n", num, val); } } int main(int argc, char *argv[]) { pthread_t t1, t2, t3; // create semaphores. val of sem1 is 1 to trigger straight away and start the whole ball rolling. if (sem_init(&trigger_sem1, 0, 1) == -1) perror("Error creating trigger_listman semaphore"); if (sem_init(&trigger_sem2, 0, 0) == -1) perror("Error creating trigger_comms semaphore"); if (sem_init(&trigger_sem3, 0, 0) == -1) perror("Error creating trigger_vws semaphore"); pthread_create(&t1, NULL, thread, (void *) 1); pthread_create(&t2, NULL, thread, (void *) 2); pthread_create(&t3, NULL, thread, (void *) 3); pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); } The following output is printed when the program is running correctly (at the start and for a random but long time after). The value of sem1 is always 1 before thread1 waits as it sleeps for 40ms, by which time sem3 has triggered it, so it wakes straight away. The other two threads wait until the semaphore is received from the previous thread. [...] sem1 wait sync sem1. val before 1 sem1 wakeup. sem1 send sync sem2. val before 0 sem2 wakeup. sem2 send sync sem3. val before 0 sem2 wait sync sem2. val before 0 sem3 wakeup. sem3 send sync sem1. val before 0 sem3 wait sync sem3. val before 0 sem1 wait sync sem1. val before 1 sem1 wakeup. sem1 send sync sem2. val before 0 [...] However, after a few hours, one of the threads begins to timeout. I can see from the output that the semaphore is being triggered, and when I print the value after the timeout is is 1. So sem_timedwait should have woken up well before the timeout. I would never expect the value of the semaphore to be 1 after the timeout, save for the very rare occasion (almost certainly never but it's possible) when the trigger happens after the timeout but before I call sem_getvalue. Also, once it begins to fail, every sem_timedwait() on that semaphore also fails in the same way. See the following output, which I've line-numbered: 01 sem3 wait sync sem3. val before 0 02 sem1 wakeup. 03 sem1 send sync sem2. val before 0 04 sem2 wakeup. 05 sem2 send sync sem3. val before 0 06 sem2 wait sync sem2. val before 0 07 sem1 wait sync sem1. val before 0 08 !!!!!! sem3 sem_timedwait failed: Connection timed out, val now 1 09 sem3 send sync sem1. val before 0 10 sem3 wait sync sem3. val before 1 11 sem3 wakeup. 12 !! sem3 not sending sync, val 1 13 sem3 wait sync sem3. val before 0 14 sem1 wakeup. [...] On line 1, thread 3 (which I have confusingly called sem1 in the printf) waits for sem3 to be triggered. On line 5, sem2 calls sem_post for sem3. However, line 8 shows sem3 timing out, but the value of the semaphore is 1. thread3 then triggers sem1 and waits again (10). However, because the value is already 1, it wakes straight away. It doesn't send sem1 again as this has all happened before control is given to thread1, however it then waits again (val is now 0) and sem1 wakes up. This now repeats for ever, sem3 always timing out and showing that the value is 1. So, my question is why does sem3 timeout, even though the semaphore has been triggered and the value is clearly 1? I would never expect to see line 08 in the output. If it times out (because, say thread 2 has crashed or is taking too long), the value should be 0. And why does it work fine for 3 or 4 hours first before getting into this state? This is using Ubuntu 9.4 with kernel 2.6.28. The same procedure has been working properly on Redhat and Fedora. But I'm now trying to port to ubuntu! Thanks for any advice, Giles

    Read the article

  • Lock Free Queue -- Single Producer, Multiple Consumers

    - by Shirish
    Hello, I am looking for a method to implement lock-free queue data structure that supports single producer, and multiple consumers. I have looked at the classic method by Maged Michael and Michael Scott (1996) but their version uses linked lists. I would like an implementation that makes use of bounded circular buffer. Something that uses atomic variables? On a side note, I am not sure why these classic methods are designed for linked lists that require a lot of dynamic memory management. In a multi-threaded program, all memory management routines are serialized. Aren't we defeating the benefits of lock-free methods by using them in conjunction with dynamic data structures? I am trying to code this in C/C++ using pthread library on a Intel 64-bit architecture. Thank you, Shirish

    Read the article

  • Lightweight spinlocks built from GCC atomic operations?

    - by Thomas
    I'd like to minimize synchronization and write lock-free code when possible in a project of mine. When absolutely necessary I'd love to substitute light-weight spinlocks built from atomic operations for pthread and win32 mutex locks. My understanding is that these are system calls underneath and could cause a context switch (which may be unnecessary for very quick critical sections where simply spinning a few times would be preferable). The atomic operations I'm referring to are well documented here: http://gcc.gnu.org/onlinedocs/gcc-4.4.1/gcc/Atomic-Builtins.html Here is an example to illustrate what I'm talking about. Imagine a RB-tree with multiple readers and writers possible. RBTree::exists() is read-only and thread safe, RBTree::insert() would require exclusive access by a single writer (and no readers) to be safe. Some code: class IntSetTest { private: unsigned short lock; RBTree<int>* myset; public: // ... void add_number(int n) { // Aquire once locked==false (atomic) while (__sync_bool_compare_and_swap(&lock, 0, 0xffff) == false); // Perform a thread-unsafe operation on the set myset->insert(n); // Unlock (atomic) __sync_bool_compare_and_swap(&lock, 0xffff, 0); } bool check_number(int n) { // Increment once the lock is below 0xffff u16 savedlock = lock; while (savedlock == 0xffff || __sync_bool_compare_and_swap(&lock, savedlock, savedlock+1) == false) savedlock = lock; // Perform read-only operation bool exists = tree->exists(n); // Decrement savedlock = lock; while (__sync_bool_compare_and_swap(&lock, savedlock, savedlock-1) == false) savedlock = lock; return exists; } }; (lets assume it need not be exception-safe) Is this code indeed thread-safe? Are there any pros/cons to this idea? Any advice? Is the use of spinlocks like this a bad idea if the threads are not truly concurrent? Thanks in advance. ;)

    Read the article

  • Total stack sizes of threads in one process

    - by David
    I use pthreads_attr_getthreadsizes() to get default stack size of one thread, 8MB on my machine. But when I create 8 threads and allocate a very large stack size to them, say hundreds of MB, the program crash. So, I guess, shall ("Number of threads" x "stack size of per thread") shall less than a value(virtual memory size)?

    Read the article

  • C++ Multithreading with pthread is blocking (including sockets)

    - by Sebastian Büttner
    I am trying to implement a multi threaded application with pthread. I did implement a thread class which looks like the following and I call it later twice (or even more), but it seems to block instead of execute the threads parallel. Here is what I got until now: The Thread Class is an abstract class which has the abstract method "exec" which should contain the thread code in a derive class (I did a sample of this, named DerivedThread) Thread.hpp #ifndef THREAD_H_ #define THREAD_H_ #include <pthread.h> class Thread { public: Thread(); void start(); void join(); virtual int exec() = 0; int exit_code(); private: static void* thread_router(void* arg); void exec_thread(); pthread_t pth_; int code_; }; #endif /* THREAD_H_ */ And Thread.cpp #include <iostream> #include "Thread.hpp" /*****************************/ using namespace std; Thread::Thread(): code_(0) { cout << "[Thread] Init" << endl; } void Thread::start() { cout << "[Thread] Created Thread" << endl; pthread_create( &pth_, NULL, Thread::thread_router, reinterpret_cast<void*>(this)); } void Thread::join() { cout << "[Thread] Join Thread" << endl; pthread_join(pth_, NULL); } int Thread::exit_code() { return code_; } void Thread::exec_thread() { cout << "[Thread] Execute" << endl; code_ = exec(); } void* Thread::thread_router(void* arg) { cout << "[Thread] exec_thread function in thread" << endl; reinterpret_cast<Thread*>(arg)->exec_thread(); return NULL; } DerivedThread.hpp #include "Thread.hpp" class DerivedThread : public Thread { public: DerivedThread(); virtual ~DerivedThread(); int exec(); void Close() = 0; DerivedThread.cpp [...] #include "DerivedThread.cpp" [...] int DerivedThread::exec() { //code to be executed do { cout << "Thread executed" << endl; usleep(1000000); } while (true); //dummy, just to let it run for a while } [...] Basically, I am calling this like the here: DerivedThread *thread; cout << "Creating Thread" << endl; thread = new DerivedThread(); cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; cout << "Creating 2nd Thread" << endl; thread = new DerivedThread(); cout << "Created 2nd thread, starting..." << endl; thread->start(); cout << "Started 2nd thread" << endl; What is working great if I am only starting one of these Threads , but if I start multiple which should run together (not synced, only parallel) . But I discovered, that the thread is created, then as it tries to execute it (via start) the problem seems to block until the thread has closed. After that the next Thread is processed. I thought that pthread would do it unblocked for me, so what did I wrong? A sample output might be: Creating Thread [Thread] Thread Init Created thread, starting... [Thread] Created thread [Thread] exec_thread function in thread [Thread] Execute Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed Thread executed .... Until Thread 1 is not terminated, a Thread 2 won't be created not executed. The process above is executed in an other class. Just for the information: I am trying to create a multi threaded server. The concept is like this: MultiThreadedServer Class has a main loop, like this one: ::inet::ServerSock *sock; //just a simple self made wrapper class for sockets DerivedThread *thread; for (;;) { sock = new ::inet::ServerSock(); this->Socket->accept( *sock ); cout << "Creating Thread" << endl; //Threads (according to code sample above) thread = new DerivedThread(sock); //I did not mentoine the parameter before as it was not neccesary, in fact, I pass the socket handle with the connected socket to the thread cout << "Created thread, starting..." << endl; thread->start(); cout << "Started thread" << endl; } So I thought that this would loop over and over and wait for new connections to accept. and when a new client arrives, I am creating a new thread and give the thread the connected socket as a parameter. In the DerivedThread::exec I am doing the handling for the connected client. Like: [...] do { [...] if (this-sock_-read( Buffer, sizeof(PacketStruc) ) 0) { cout << "[Handler_Base] Recv Packet" << endl; //handle the packet } else { Connected = false; } delete Buffer; } while ( Connected ); So I loop in the created thread as long as the client keeps the connection. I think, that the socket may cause the blocking behaviour. Edit: I figured out, that it is not the read() loop in the DerivedThread Class as I simply replaced it with a loop over a simple cout-usleep part. It did also only execute the first one and after first thread finished, the 2nd one was executed. Many thanks and best regards, Sebastian

    Read the article

  • Using pthread to perform matrix multiplication

    - by shadyabhi
    I have both matrices containing only ones and each array has 500 rows and columns. So, the resulting matrix should be a matrix of all elements having value 500. But, I am getting res_mat[0][0]=5000. Even other elements are also 5000. Why? #include<stdio.h> #include<pthread.h> #include<unistd.h> #include<stdlib.h> #define ROWS 500 #define COLUMNS 500 #define N_THREADS 10 int mat1[ROWS][COLUMNS],mat2[ROWS][COLUMNS],res_mat[ROWS][COLUMNS]; void *mult_thread(void *t) { /*This function calculates 50 ROWS of the matrix*/ int starting_row; starting_row = *((int *)t); starting_row = 50 * starting_row; int i,j,k; for (i = starting_row;i<starting_row+50;i++) for (j=0;j<COLUMNS;j++) for (k=0;k<ROWS;k++) res_mat[i][j] += (mat1[i][k] * mat2[k][j]); return; } void fill_matrix(int mat[ROWS][COLUMNS]) { int i,j; for(i=0;i<ROWS;i++) for(j=0;j<COLUMNS;j++) mat[i][j] = 1; } int main() { int n_threads = 10; //10 threads created bcos we have 500 rows and one thread calculates 50 rows int j=0; pthread_t p[n_threads]; fill_matrix(mat1); fill_matrix(mat2); for (j=0;j<10;j++) pthread_create(&p[j],NULL,mult_thread,&j); for (j=0;j<10;j++) pthread_join(p[j],NULL); printf("%d\n",res_mat[0][0]); return 0; }

    Read the article

  • Suggestions for duplicate file finder algorithm (using C)

    - by Andrei Ciobanu
    Hello, I wanted to write a program that test if two files are duplicates (have exactly the same content). First I test if the files have the same sizes, and if they have i start to compare their contents. My first idea, was to "split" the files into fixed size blocks, then start a thread for every block, fseek to startup character of every block and continue the comparisons in parallel. When a comparison from a thread fails, the other working threads are canceled, and the program exits out of the thread spawning loop. The code looks like this: dupf.h #ifndef __NM__DUPF__H__ #define __NM__DUPF__H__ #define NUM_THREADS 15 #define BLOCK_SIZE 8192 /* Thread argument structure */ struct thread_arg_s { const char *name_f1; /* First file name */ const char *name_f2; /* Second file name */ int cursor; /* Where to seek in the file */ }; typedef struct thread_arg_s thread_arg; /** * 'arg' is of type thread_arg. * Checks if the specified file blocks are * duplicates. */ void *check_block_dup(void *arg); /** * Checks if two files are duplicates */ int check_dup(const char *name_f1, const char *name_f2); /** * Returns a valid pointer to a file. * If the file (given by the path/name 'fname') cannot be opened * in 'mode', the program is interrupted an error message is shown. **/ FILE *safe_fopen(const char *name, const char *mode); #endif dupf.c #include <errno.h> #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "dupf.h" FILE *safe_fopen(const char *fname, const char *mode) { FILE *f = NULL; f = fopen(fname, mode); if (f == NULL) { char emsg[255]; sprintf(emsg, "FOPEN() %s\t", fname); perror(emsg); exit(-1); } return (f); } void *check_block_dup(void *arg) { const char *name_f1 = NULL, *name_f2 = NULL; /* File names */ FILE *f1 = NULL, *f2 = NULL; /* Streams */ int cursor = 0; /* Reading cursor */ char buff_f1[BLOCK_SIZE], buff_f2[BLOCK_SIZE]; /* Character buffers */ int rchars_1, rchars_2; /* Readed characters */ /* Initializing variables from 'arg' */ name_f1 = ((thread_arg*)arg)->name_f1; name_f2 = ((thread_arg*)arg)->name_f2; cursor = ((thread_arg*)arg)->cursor; /* Opening files */ f1 = safe_fopen(name_f1, "r"); f2 = safe_fopen(name_f2, "r"); /* Setup cursor in files */ fseek(f1, cursor, SEEK_SET); fseek(f2, cursor, SEEK_SET); /* Initialize buffers */ rchars_1 = fread(buff_f1, 1, BLOCK_SIZE, f1); rchars_2 = fread(buff_f2, 1, BLOCK_SIZE, f2); if (rchars_1 != rchars_2) { /* fread failed to read the same portion. * program cannot continue */ perror("ERROR WHEN READING BLOCK"); exit(-1); } while (rchars_1-->0) { if (buff_f1[rchars_1] != buff_f2[rchars_1]) { /* Different characters */ fclose(f1); fclose(f2); pthread_exit("notdup"); } } /* Close streams */ fclose(f1); fclose(f2); pthread_exit("dup"); } int check_dup(const char *name_f1, const char *name_f2) { int num_blocks = 0; /* Number of 'blocks' to check */ int num_tsp = 0; /* Number of threads spawns */ int tsp_iter = 0; /* Iterator for threads spawns */ pthread_t *tsp_threads = NULL; thread_arg *tsp_threads_args = NULL; int tsp_threads_iter = 0; int thread_c_res = 0; /* Thread creation result */ int thread_j_res = 0; /* Thread join res */ int loop_res = 0; /* Function result */ int cursor; struct stat buf_f1; struct stat buf_f2; if (name_f1 == NULL || name_f2 == NULL) { /* Invalid input parameters */ perror("INVALID FNAMES\t"); return (-1); } if (stat(name_f1, &buf_f1) != 0 || stat(name_f2, &buf_f2) != 0) { /* Stat fails */ char emsg[255]; sprintf(emsg, "STAT() ERROR: %s %s\t", name_f1, name_f2); perror(emsg); return (-1); } if (buf_f1.st_size != buf_f2.st_size) { /* File have different sizes */ return (1); } /* Files have the same size, function exec. is continued */ num_blocks = (buf_f1.st_size / BLOCK_SIZE) + 1; num_tsp = (num_blocks / NUM_THREADS) + 1; cursor = 0; for (tsp_iter = 0; tsp_iter < num_tsp; tsp_iter++) { loop_res = 0; /* Create threads array for this spawn */ tsp_threads = malloc(NUM_THREADS * sizeof(*tsp_threads)); if (tsp_threads == NULL) { perror("TSP_THREADS ALLOC FAILURE\t"); return (-1); } /* Create arguments for every thread in the current spawn */ tsp_threads_args = malloc(NUM_THREADS * sizeof(*tsp_threads_args)); if (tsp_threads_args == NULL) { perror("TSP THREADS ARGS ALLOCA FAILURE\t"); return (-1); } /* Initialize arguments and create threads */ for (tsp_threads_iter = 0; tsp_threads_iter < NUM_THREADS; tsp_threads_iter++) { if (cursor >= buf_f1.st_size) { break; } tsp_threads_args[tsp_threads_iter].name_f1 = name_f1; tsp_threads_args[tsp_threads_iter].name_f2 = name_f2; tsp_threads_args[tsp_threads_iter].cursor = cursor; thread_c_res = pthread_create( &tsp_threads[tsp_threads_iter], NULL, check_block_dup, (void*)&tsp_threads_args[tsp_threads_iter]); if (thread_c_res != 0) { perror("THREAD CREATION FAILURE"); return (-1); } cursor+=BLOCK_SIZE; } /* Join last threads and get their status */ while (tsp_threads_iter-->0) { void *thread_res = NULL; thread_j_res = pthread_join(tsp_threads[tsp_threads_iter], &thread_res); if (thread_j_res != 0) { perror("THREAD JOIN FAILURE"); return (-1); } if (strcmp((char*)thread_res, "notdup")==0) { loop_res++; /* Closing other threads and exiting by condition * from loop. */ while (tsp_threads_iter-->0) { pthread_cancel(tsp_threads[tsp_threads_iter]); } } } free(tsp_threads); free(tsp_threads_args); if (loop_res > 0) { break; } } return (loop_res > 0) ? 1 : 0; } The function works fine (at least for what I've tested). Still, some guys from #C (freenode) suggested that the solution is overly complicated, and it may perform poorly because of parallel reading on hddisk. What I want to know: Is the threaded approach flawed by default ? Is fseek() so slow ? Is there a way to somehow map the files to memory and then compare them ?

    Read the article

  • CPU Affinity Masks (Putting Threads on different CPUs)

    - by hahuang65
    I have 4 threads, and I am trying to set thread 1 to run on CPU 1, thread 2 on CPU 2, etc. However, when I run my code below, the affinity masks are returning the correct values, but when I do a sched_getcpu() on the threads, they all return that they are running on CPU 4. Anybody know what my problem here is? Thanks in advance! #define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <sched.h> #include <errno.h> void *pthread_Message(char *message) { printf("%s is running on CPU %d\n", message, sched_getcpu()); } int main() { pthread_t thread1, thread2, thread3, thread4; pthread_t threadArray[4]; cpu_set_t cpu1, cpu2, cpu3, cpu4; char *thread1Msg = "Thread 1"; char *thread2Msg = "Thread 2"; char *thread3Msg = "Thread 3"; char *thread4Msg = "Thread 4"; int thread1Create, thread2Create, thread3Create, thread4Create, i, temp; CPU_ZERO(&cpu1); CPU_SET(1, &cpu1); temp = pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpu1); printf("Set returned by pthread_getaffinity_np() contained:\n"); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu1)) printf("CPU1: CPU %d\n", i); CPU_ZERO(&cpu2); CPU_SET(2, &cpu2); temp = pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpu2); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu2)) printf("CPU2: CPU %d\n", i); CPU_ZERO(&cpu3); CPU_SET(3, &cpu3); temp = pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpu3); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu3)) printf("CPU3: CPU %d\n", i); CPU_ZERO(&cpu4); CPU_SET(4, &cpu4); temp = pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpu4); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu4)) printf("CPU4: CPU %d\n", i); thread1Create = pthread_create(&thread1, NULL, (void *)pthread_Message, thread1Msg); thread2Create = pthread_create(&thread2, NULL, (void *)pthread_Message, thread2Msg); thread3Create = pthread_create(&thread3, NULL, (void *)pthread_Message, thread3Msg); thread4Create = pthread_create(&thread4, NULL, (void *)pthread_Message, thread4Msg); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); return 0; }

    Read the article

  • How to mult-thread this?

    - by WilliamKF
    I wish to have two threads. The first thread1 occasionally calls the following pseudo function: void waitForThread2() { if (thread2 is not idle) { return; } notifyThread2IamReady(); while (thread2IsExclusive) { } } The second thread2 is forever in the following pseudo loop: for (;;) { Notify thread1 I am idle. while (!thread1IsReady()) { } Notify thread1 I am exclusive. Do some work while thread1 is blocked. Notify thread1 I am busy. Do some work in parallel with thread1. } What is the best way to write this such that both thread1 and thread2 are kept as busy as possible on a machine with multiple cores. I would like to avoid long delays between notification in one thread and detection by the other. I tried using pthread condition variables but found the delay between thread2 doing 'notify thread1 I am busy' and the loop in waitForThread2() on thear2IsExclusive() can be up to almost one second delay. I then tried using a volatile sig_atomic_t shared variable to control the same, but something is going wrong, so I must not be doing it correctly.

    Read the article

< Previous Page | 1 2 3 4 5 6 7  | Next Page >