c++ - Is my function thread-safe and reentrant? -
i have function called 2 threads each having local copy of vector. assumption since each thread has different vector function below thread-safe.
below function thread-safe , reentrant?
int partition(int high, int low, int pivot, std::vector<int>& arr) { int j = low; (int = low ; <= high ; i++) { if (arr[i] <= pivot) { swap(i , j++ , arr); } } return arr.size() - j; } void swap(int fromindex , int toindex , std::vector<int> &arr) { arr[fromindex] = arr[fromindex]^arr[toindex]; arr[toindex] = arr[fromindex]^arr[toindex]; arr[fromindex] = arr[fromindex]^arr[toindex]; }
the function not thread-safe, because possible pass same vector different threads.
however, possible write thread-safe code using non-thread-safe functions if synchronization outside of these functions. i.e. if calling code takes care same vector never passed function @ same time, the calling code thread-safe.
about being re-entrant, wikipedia has following say:
in computing, computer program or subroutine called reentrant if can interrupted in middle of execution , safely called again ("re-entered") before previous invocations complete execution. interruption caused internal action such jump or call, or external action such hardware interrupt or signal. once reentered invocation completes, previous invocations resume correct execution.
i emphasized last part in definition, because obviously, function not thread-safe may not execute correctly , therefore cannot reentrant definition.
Comments
Post a Comment