user16468058
user16468058

Reputation:

test_and_set_bit How It Works?

Can someone kindly answer my questions under the accepted answer?

I was reading: https://www.kernel.org/doc/htmldocs/kernel-api/API-test-and-set-bit.html but didn't understand that much.

Sorry but that page wasn't clear at all.


Usage:

typedef struct lock {
  bool is_locked;
} lock_t;

void init(lock_t* l) {
  l->is_locked = 0;
}

void lock(lock_t* l) {
  while (test_and_set_bit
    (l->is_locked));
}

void unlock(lock_t* l) {
  l->is_locked = 0;
}

Upvotes: 2

Views: 1134

Answers (1)

A M
A M

Reputation: 15265

If the bit was already 1 does it stay 1 or 0?

It will be set to 1

If it's 0 and I'm not wrong then it changes to 1?

Yes, it changes to 1

What is "bit" here, an input can be bool which is byte not bit...

Bit is one single bit. Not a byte. Input cannot be bool. If you have for example an unsigned char it consists of 8 Bits

By return do they mean that after changing the value we change in back to its original condition? if so then this is useless...

No. The function will return the value of the bit as it was before. The function then sets the bit to 1

In C++ when I try to call it I get: Use of undeclared identifier 'test_and_set_bit'

In standard C++ this function is not available. It is a function that is defined in an external library.

Upvotes: 4

Related Questions