0

The following code pieces are been called regularly by multiple threads in a single process. The question here is, are there critical sections?

First Code:

struct object {
    struct object *nxt;
};

void delete(object **top, object *deletable) {
    object *current, *pred;
    if (*top == deletable) {
        *top = deletable->nxt;
} else {
    pred = top;
    current = (*top)->nxt;
    while (current && (current != deletable)) {
        pred = current;
        current = current->nxt;
    }
    if (current) {
        pred = current->nxt;
    }
}

Second Code;

int shift(int param) {
    int result = 654321;
    result = result ^ param;
    param = param * result;
    result = (param >> 9) ^ ~result;
    return result;
}

Currently i don't think that there are any critical sections, because the variables don't manipulate the same data. But I am not sure about this. I am pretty new to critical sections and multithreading.

Dos
  • 67
  • 7
  • Is it possible that an outer caller will call these functions as well? The functions doesn't have any internal states, but when accessing the data structures a parallel call of them could cause serious trouble. So my recommendation: lock them when using them. – KimKulling Jan 16 '17 at 16:43
  • thanks for the answer! what exactly do you mean by outer caller? its been given, that multiple threads in a single process are running the code pieces, but no other processes or threads in other processes are running the code pieces. – Dos Jan 16 '17 at 16:48
  • @Dos to answer the question you asked: No there are not, there are no synchronization primitives at all in any of that code. However that's not necessarily a bad thing if the data being operated on is only ever touched from one thread at a time and you can prove this. – Mgetz Jan 16 '17 at 16:50
  • The first one is a linked list implementation - If you can guarantee that each thread operates on its own list (and list elements), you're safe. If not, you'll definitely get into trouble. The second one should generally be safe. – tofro Jan 16 '17 at 17:02
  • 1
    @Dos Realize first that thread-safety is not so much about *code* being shared between threads - It's about *data* that may be manipulated concurrently – tofro Jan 16 '17 at 17:07

1 Answers1

2

There are no global and/or static variables in your code.

There are no other types of shared resources (e.g., the same file used in different places).

Therefore, there are no critical sections here.

barak manos
  • 29,648
  • 10
  • 62
  • 114