blob: ed697358409202fc87d092c816b7d4c2fcbb4a49 [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/* Copyright (C) 2002, 2003 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, write to the Free
17 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 02111-1307 USA. */
19
20#include <errno.h>
21#include "pthreadP.h"
22#include <atomic.h>
23
24
25int
26attribute_protected
27__pthread_setcancelstate (
28 int state,
29 int *oldstate)
30{
31 volatile struct pthread *self;
32
33 if (state < PTHREAD_CANCEL_ENABLE || state > PTHREAD_CANCEL_DISABLE)
34 return EINVAL;
35
36 self = THREAD_SELF;
37
38 int oldval = THREAD_GETMEM (self, cancelhandling);
39 while (1)
40 {
41 int newval = (state == PTHREAD_CANCEL_DISABLE
42 ? oldval | CANCELSTATE_BITMASK
43 : oldval & ~CANCELSTATE_BITMASK);
44
45 /* Store the old value. */
46 if (oldstate != NULL)
47 *oldstate = ((oldval & CANCELSTATE_BITMASK)
48 ? PTHREAD_CANCEL_DISABLE : PTHREAD_CANCEL_ENABLE);
49
50 /* Avoid doing unnecessary work. The atomic operation can
51 potentially be expensive if the memory has to be locked and
52 remote cache lines have to be invalidated. */
53 if (oldval == newval)
54 break;
55
56 /* Update the cancel handling word. This has to be done
57 atomically since other bits could be modified as well. */
58 int curval = THREAD_ATOMIC_CMPXCHG_VAL (self, cancelhandling, newval,
59 oldval);
60 if (__builtin_expect (curval == oldval, 1))
61 {
62 if (CANCEL_ENABLED_AND_CANCELED_AND_ASYNCHRONOUS (newval))
63 __do_cancel ();
64
65 break;
66 }
67
68 /* Prepare for the next round. */
69 oldval = curval;
70 }
71
72 return 0;
73}
74strong_alias (__pthread_setcancelstate, pthread_setcancelstate)