-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path_concurrency.c
1925 lines (1610 loc) · 50.8 KB
/
_concurrency.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) Meta Platforms, Inc. and affiliates. */
#include "ft_utils.h"
/* Begin ConcurrentDict
***********************
*/
typedef struct {
PyObject_HEAD PyObject** buckets;
Py_ssize_t size;
PyObject* weakreflist;
} ConcurrentDictObject;
static int ConcurrentDict_clear(ConcurrentDictObject* self) {
if (self->buckets) {
for (Py_ssize_t i = 0; i < self->size; i++) {
Py_CLEAR(self->buckets[i]);
}
PyMem_Free(self->buckets);
self->buckets = NULL;
self->size = 0;
}
return 0;
}
static void ConcurrentDict_dealloc(ConcurrentDictObject* self) {
PyObject_GC_UnTrack(self);
ConcurrentDict_clear(self);
PyObject_ClearWeakRefs((PyObject*)self);
PyObject_GC_Del(self);
}
static PyObject*
ConcurrentDict_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
Py_ssize_t initial_capacity = 17;
static char* kwlist[] = {"initial_capacity", NULL};
if (!PyArg_ParseTupleAndKeywords(
args, kwds, "|n", kwlist, &initial_capacity)) {
return NULL;
}
ConcurrentDictObject* self = (ConcurrentDictObject*)type->tp_alloc(type, 0);
if (self != NULL) {
self->buckets =
(PyObject**)PyMem_Calloc(initial_capacity, sizeof(PyObject*));
if (!self->buckets) {
PyErr_NoMemory();
Py_DECREF(self);
return NULL;
}
self->size = initial_capacity;
for (Py_ssize_t i = 0; i < initial_capacity; i++) {
self->buckets[i] = PyDict_New();
if (!self->buckets[i]) {
Py_DECREF(self);
return NULL;
}
}
}
return (PyObject*)self;
}
static PyObject* ConcurrentDict_getitem(
ConcurrentDictObject* self,
PyObject* key) {
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1 && PyErr_Occurred()) {
return NULL;
}
Py_ssize_t index = hash % self->size;
if (index < 0) {
index = -index;
}
PyObject* value = PyDict_GetItem(self->buckets[index], key);
if (!value) {
PyErr_SetObject(PyExc_KeyError, key);
return NULL;
}
Py_INCREF(value);
return value;
}
static int ConcurrentDict_setitem(
ConcurrentDictObject* self,
PyObject* key,
PyObject* value) {
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1 && PyErr_Occurred()) {
return -1;
}
Py_ssize_t index = hash % self->size;
if (index < 0) {
index = -index;
}
if (value == NULL) {
if (PyDict_DelItem(self->buckets[index], key) < 0) {
return -1;
}
} else {
if (PyDict_SetItem(self->buckets[index], key, value) < 0) {
return -1;
}
}
return 0;
}
static int ConcurrentDict_contains(ConcurrentDictObject* self, PyObject* key) {
Py_hash_t hash = PyObject_Hash(key);
if (hash == -1 && PyErr_Occurred()) {
return -1;
}
Py_ssize_t index = hash % self->size;
if (index < 0) {
index = -index;
}
return PyDict_Contains(self->buckets[index], key);
}
static PyObject* ConcurrentDict_as_dict(
ConcurrentDictObject* self,
PyObject* Py_UNUSED(args)) {
PyObject* dict = PyDict_New();
if (!dict) {
return NULL;
}
for (Py_ssize_t i = 0; i < self->size; i++) {
if (self->buckets[i]) {
if (PyDict_Update(dict, self->buckets[i]) != 0) {
Py_DECREF(dict);
return NULL;
}
}
}
return dict;
}
static int ConcurrentDict_traverse(
ConcurrentDictObject* self,
visitproc visit,
void* arg) {
Py_ssize_t i;
for (i = 0; i < self->size; i++) {
Py_VISIT(self->buckets[i]);
}
return 0;
}
static PyMappingMethods ConcurrentDict_mapping = {
(lenfunc)0, // mp_length
(binaryfunc)ConcurrentDict_getitem, // mp_subscript
(objobjargproc)ConcurrentDict_setitem, // mp_ass_subscript
};
static PySequenceMethods ConcurrentDict_sequence = {
.sq_contains = (objobjproc)ConcurrentDict_contains,
};
static PyMethodDef ConcurrentDict_methods[] = {
{"as_dict",
(PyCFunction)ConcurrentDict_as_dict,
METH_NOARGS,
PyDoc_STR(
"Create a dict from the key value pairs in this ConcurrentDict. Not thread consistent.")},
{NULL, NULL, 0, NULL}};
static PyTypeObject ConcurrentDictType = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "_concurrency.ConcurrentDict",
.tp_doc = "Concurrent Dictionary",
.tp_basicsize = sizeof(ConcurrentDictObject),
.tp_itemsize = 0,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_as_mapping = &ConcurrentDict_mapping,
.tp_as_sequence = &ConcurrentDict_sequence,
.tp_methods = ConcurrentDict_methods,
.tp_new = ConcurrentDict_new,
.tp_dealloc = (destructor)ConcurrentDict_dealloc,
.tp_traverse = (traverseproc)ConcurrentDict_traverse,
.tp_clear = (inquiry)ConcurrentDict_clear,
.tp_weaklistoffset = offsetof(ConcurrentDictObject, weakreflist),
};
/* ******************
End ConcurrentDict
*/
/* Begin AtomicInt64
*******************
*/
typedef struct {
PyObject_HEAD int64_t value;
PyObject* weakreflist;
} AtomicInt64Object;
static PyTypeObject AtomicInt64Type;
static PyObject*
atomicint64_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
AtomicInt64Object* self;
int64_t value = 0;
if (!PyArg_ParseTuple(args, "|L", &value)) {
return NULL;
}
self = (AtomicInt64Object*)type->tp_alloc(type, 0);
if (self == NULL) {
return NULL;
}
self->weakreflist = NULL;
_Py_atomic_store_int64(&self->value, value);
return (PyObject*)self;
}
static int
atomicint64_init(AtomicInt64Object* self, PyObject* args, PyObject* kwds) {
return 0;
}
static void atomicint64_dealloc(AtomicInt64Object* self) {
PyObject_ClearWeakRefs((PyObject*)self);
Py_TYPE(self)->tp_free((PyObject*)self);
}
#define GET_I64_OR_ERROR(other) \
int64_t value; \
do { \
if (PyLong_CheckExact(other)) { \
value = PyLong_AsLongLong(other); \
} else if (PyObject_TypeCheck(other, &AtomicInt64Type)) { \
value = _Py_atomic_load_int64(&((AtomicInt64Object*)other)->value); \
} else { \
PyErr_SetString(PyExc_TypeError, "unsupported operand type(s)"); \
return NULL; \
} \
} while (0)
static PyObject* atomicint64_add(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) + value);
}
static PyObject* atomicint64_sub(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) - value);
}
static PyObject* atomicint64_mul(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) * value);
}
static PyObject* atomicint64_div(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
if (value == 0) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
return NULL;
}
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) / value);
}
static PyObject* atomicint64_iadd(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
_Py_atomic_add_int64(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_isub(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
atomic_int64_sub(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_imul(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
atomic_int64_mul(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_idiv(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
if (value == 0) {
PyErr_SetString(PyExc_ZeroDivisionError, "division by zero");
return NULL;
}
atomic_int64_div(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static int atomicint64_bool(AtomicInt64Object* self) {
return _Py_atomic_load_int64(&self->value) != 0;
}
static PyObject* atomicint64_int(AtomicInt64Object* self) {
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value));
}
static PyObject* atomicint64_neg(AtomicInt64Object* self) {
return PyLong_FromLongLong(-_Py_atomic_load_int64(&self->value));
}
static PyObject* atomicint64_pos(AtomicInt64Object* self) {
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value));
}
static PyObject* atomicint64_abs(AtomicInt64Object* self) {
int64_t value = _Py_atomic_load_int64(&self->value);
if (value < 0) {
value = -value;
}
return PyLong_FromLongLong(value);
}
static PyObject* atomicint64_format(AtomicInt64Object* self, PyObject* args) {
PyObject* int_obj = atomicint64_int(self);
if (int_obj == NULL)
return NULL;
PyObject* format_spec;
if (!PyArg_ParseTuple(args, "O", &format_spec))
return NULL;
Py_INCREF(format_spec);
PyObject* result = PyObject_Format(int_obj, format_spec);
Py_DECREF(int_obj);
Py_DECREF(format_spec);
return result;
}
static PyObject*
atomicint64_richcompare(AtomicInt64Object* self, PyObject* other, int op) {
PyObject* int_obj = atomicint64_int(self);
if (int_obj == NULL)
return NULL;
int result = PyObject_RichCompareBool(int_obj, other, op);
Py_DECREF(int_obj);
if (result == -1)
return NULL;
else
return PyBool_FromLong(result);
}
static PyObject* atomicint64_ior(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
atomic_int64_or(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_ixor(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
atomic_int64_xor(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_iand(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
atomic_int64_and(&self->value, value);
Py_INCREF(self);
return (PyObject*)self;
}
static PyObject* atomicint64_or(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) | value);
}
static PyObject* atomicint64_xor(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) ^ value);
}
static PyObject* atomicint64_and(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value) & value);
}
static PyObject* atomicint64_not(AtomicInt64Object* self) {
return PyLong_FromLongLong(~_Py_atomic_load_int64(&self->value));
}
static PyObject* atomicint64_set(AtomicInt64Object* self, PyObject* other) {
GET_I64_OR_ERROR(other);
_Py_atomic_store_int64(&self->value, value);
Py_RETURN_NONE;
}
static PyObject* atomicint64_get(AtomicInt64Object* self) {
return PyLong_FromLongLong(_Py_atomic_load_int64(&self->value));
}
static PyObject* atomicint64_incr(AtomicInt64Object* self) {
return PyLong_FromLongLong(_Py_atomic_add_int64(&self->value, 1) + 1);
}
static PyObject* atomicint64_decr(AtomicInt64Object* self) {
return PyLong_FromLongLong(_Py_atomic_add_int64(&self->value, -1) - 1);
}
static PyMethodDef atomicint64_methods[] = {
{"set", (PyCFunction)atomicint64_set, METH_O, "Atomically set the value"},
{"get",
(PyCFunction)atomicint64_get,
METH_NOARGS,
"Atomically get the value"},
{"incr",
(PyCFunction)atomicint64_incr,
METH_NOARGS,
"Atomically ++ and return new value"},
{"decr",
(PyCFunction)atomicint64_decr,
METH_NOARGS,
"Atomically -- and return new value"},
{"__format__",
(PyCFunction)atomicint64_format,
METH_VARARGS,
"Format the value"},
{NULL, NULL, 0, NULL}};
static PyNumberMethods atomicint64_as_number = {
.nb_add = (binaryfunc)atomicint64_add,
.nb_subtract = (binaryfunc)atomicint64_sub,
.nb_multiply = (binaryfunc)atomicint64_mul,
.nb_floor_divide = (binaryfunc)atomicint64_div,
.nb_negative = (unaryfunc)atomicint64_neg,
.nb_positive = (unaryfunc)atomicint64_pos,
.nb_absolute = (unaryfunc)atomicint64_abs,
.nb_bool = (inquiry)atomicint64_bool,
.nb_or = (binaryfunc)atomicint64_or,
.nb_xor = (binaryfunc)atomicint64_xor,
.nb_and = (binaryfunc)atomicint64_and,
.nb_invert = (unaryfunc)atomicint64_not,
.nb_inplace_add = (binaryfunc)atomicint64_iadd,
.nb_inplace_subtract = (binaryfunc)atomicint64_isub,
.nb_inplace_multiply = (binaryfunc)atomicint64_imul,
.nb_inplace_floor_divide = (binaryfunc)atomicint64_idiv,
.nb_int = (unaryfunc)atomicint64_int,
.nb_inplace_or = (binaryfunc)atomicint64_ior,
.nb_inplace_xor = (binaryfunc)atomicint64_ixor,
.nb_inplace_and = (binaryfunc)atomicint64_iand,
};
static PyTypeObject AtomicInt64Type = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "_concurrency.AtomicInt64",
.tp_basicsize = sizeof(AtomicInt64Object),
.tp_itemsize = 0,
.tp_dealloc = (destructor)atomicint64_dealloc,
.tp_as_number = &atomicint64_as_number,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
.tp_doc = "AtomicInt64 objects",
.tp_init = (initproc)atomicint64_init,
.tp_new = atomicint64_new,
.tp_methods = atomicint64_methods,
.tp_richcompare = (richcmpfunc)atomicint64_richcompare,
.tp_weaklistoffset = offsetof(AtomicInt64Object, weakreflist),
};
/* ***************
End AtomicInt64
*/
/* Begin AtomicReference
***********************
*/
typedef struct {
PyObject_HEAD PyObject* ref;
PyObject* weakreflist;
} AtomicReferenceObject;
static PyObject*
atomicreference_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
if (PyTuple_GET_SIZE(args) > 1) {
PyErr_SetString(
PyExc_TypeError, "AtomicReference() takes zero or one argument");
return NULL;
}
AtomicReferenceObject* self = (AtomicReferenceObject*)type->tp_alloc(type, 0);
if (self == NULL) {
return NULL;
}
self->weakreflist = NULL;
if (PyTuple_GET_SIZE(args) == 1) {
PyObject* obj = PyTuple_GET_ITEM(args, 0);
self->ref = obj;
} else {
self->ref = Py_None;
}
ConcurrentRegisterReference(self->ref);
Py_INCREF(self->ref);
return (PyObject*)self;
}
static int atomicreference_clear(AtomicReferenceObject* self) {
Py_CLEAR(self->ref);
return 0;
}
static void atomicreference_dealloc(AtomicReferenceObject* self) {
PyObject_GC_UnTrack(self);
atomicreference_clear(self);
PyObject_ClearWeakRefs((PyObject*)self);
PyObject_GC_Del(self);
}
static int atomicreference_traverse(
AtomicReferenceObject* self,
visitproc visit,
void* arg) {
Py_VISIT(_Py_atomic_load_ptr(&self->ref));
return 0;
}
static PyObject* atomicreference_get(AtomicReferenceObject* self) {
return ConcurrentGetNewReference(&self->ref);
}
static PyObject* atomicreference_exchange(
AtomicReferenceObject* self,
PyObject* obj) {
ConcurrentRegisterReference(obj);
Py_INCREF(obj);
return _Py_atomic_exchange_ptr(&self->ref, obj);
}
static PyObject* atomicreference_set(
AtomicReferenceObject* self,
PyObject* obj) {
ConcurrentRegisterReference(obj);
Py_INCREF(obj);
PyObject* ret = _Py_atomic_exchange_ptr(&self->ref, obj);
Py_DECREF(ret);
Py_RETURN_NONE;
}
static PyObject* atomicreference_compare_exchange(
AtomicReferenceObject* self,
PyObject* args) {
PyObject* expected;
PyObject* obj;
if (!PyArg_ParseTuple(args, "OO", &expected, &obj)) {
return NULL;
}
ConcurrentRegisterReference(obj);
Py_INCREF(obj);
if (!_Py_atomic_compare_exchange_ptr(&self->ref, &expected, obj)) {
Py_DECREF(obj);
Py_RETURN_FALSE;
}
Py_DECREF(expected);
Py_RETURN_TRUE;
}
static PyMethodDef AtomicReference_methods[] = {
{"set", (PyCFunction)atomicreference_set, METH_O},
{"get", (PyCFunction)atomicreference_get, METH_NOARGS},
{"exchange", (PyCFunction)atomicreference_exchange, METH_O},
{"compare_exchange",
(PyCFunction)atomicreference_compare_exchange,
METH_VARARGS},
{NULL}};
static PyTypeObject AtomicReferenceType = {
PyVarObject_HEAD_INIT(NULL, 0).tp_name = "_concurrency.AtomicReference",
.tp_basicsize = sizeof(AtomicReferenceObject),
.tp_dealloc = (destructor)atomicreference_dealloc,
.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
.tp_doc = "AtomicReference",
.tp_traverse = (traverseproc)atomicreference_traverse,
.tp_clear = (inquiry)atomicreference_clear,
.tp_methods = AtomicReference_methods,
.tp_new = atomicreference_new,
.tp_weaklistoffset = offsetof(AtomicReferenceObject, weakreflist),
};
/* ******************
End AtomicReference
*/
/* Begin ConcurrentDeque
***********************
*/
/* A node represents a single datum in the deque. It is a doubly-linked list
* node that contains a pointer to the datum.
*/
typedef struct ConcurrentDequeNode {
struct ConcurrentDequeNode* prev;
struct ConcurrentDequeNode* next;
PyObject* datum;
} ConcurrentDequeNode;
/* A list represents the bounds of the deque. We allocate it in a separate
* object to allow it to be replaced atomically from within the deque, allowing
* these objects to be used concurrently.
*/
typedef struct {
ConcurrentDequeNode* head;
ConcurrentDequeNode* tail;
} ConcurrentDequeList;
/* A deque is a doubly-sided queue that is optimized for adding and removing
* items at the ends. It maintains a list object that contains a pointer to its
* head and tail nodes.
*/
typedef struct {
/* The list field in this struct is a tagged pointer. If the
* least-significant bit is set, then list is considered "locked". This
* happens when the list has just been replaced and one of the operations
* needs to fix internal links within the linked-list. Because this is a
* tagged pointer, it is not safe for reading without considering the lock
* state. Note that we can do this tagging because of the alignment of the
* list field.
*/
PyObject_HEAD ConcurrentDequeList* list;
PyObject* weakreflist;
} ConcurrentDequeObject;
/* Allocate a new node for the deque and return a pointer to it.
*/
static ConcurrentDequeNode* ConcurrentDequeNode_alloc(
PyObject* datum,
ConcurrentDequeNode* prev,
ConcurrentDequeNode* next) {
ConcurrentDequeNode* node = PyMem_Malloc(sizeof(ConcurrentDequeNode));
if (node == NULL) {
PyErr_NoMemory();
return NULL;
}
node->prev = prev;
node->next = next;
Py_INCREF(datum);
node->datum = datum;
return node;
}
/* Deallocate a node object, using Python's memory management. We have this here
* to signify to the reader that we know we're only freeing the node and
* purposefully not decrementing the reference count of the datum.
*/
#define ConcurrentDequeNode_dealloc_shallow PyMem_Free
/* Deallocate a node and remove its reference to the datum.
*/
static void ConcurrentDequeNode_dealloc(ConcurrentDequeNode* node) {
Py_DECREF(node->datum);
ConcurrentDequeNode_dealloc_shallow(node);
}
/* Deallocate a chain of nodes, starting at the given node.
*/
static void ConcurrentDequeNode_dealloc_chain(ConcurrentDequeNode* node) {
while (node != NULL) {
ConcurrentDequeNode* next = node->next;
ConcurrentDequeNode_dealloc(node);
node = next;
}
}
/* Allocate the internal list object that is used by the deque to hold its
* contents.
*/
static ConcurrentDequeList* ConcurrentDequeList_alloc(
ConcurrentDequeNode* head,
ConcurrentDequeNode* tail) {
ConcurrentDequeList* list = PyMem_Malloc(sizeof(ConcurrentDequeList));
if (list == NULL) {
PyErr_NoMemory();
return NULL;
}
list->head = head;
list->tail = tail;
return list;
}
/* Deallocate a list object, using Python's memory management. We have this here
* to signify to the reader that we know we're only freeing the list and not the
* nodes in the list.
*/
#define ConcurrentDequeList_dealloc_shallow PyMem_Free
/* Deallocate and remove references to the given list by visiting each node in
* the doubly-linked list.
*/
static void ConcurrentDequeList_dealloc(ConcurrentDequeList* list) {
ConcurrentDequeNode_dealloc_chain(list->head);
ConcurrentDequeList_dealloc_shallow(list);
}
/* Atomically replace the list pointer on the given deque. This purposefully
* does not take into account the locking bit, and therefore should only be
* called when the list is known to be locked.
*/
#define ConcurrentDeque_replace(deque_, list_) \
_Py_atomic_store_ptr((void**)&deque_->list, list_)
/* Attempt to atomically replace the list pointer on the given deque with the
* given list.
*/
#define ConcurrentDeque_try_replace(deque_, list_, next_list_) \
_Py_atomic_compare_exchange_ptr(&deque_->list, list_, next_list_)
/* Lock the given list by turning on its least significant bit.
*/
#define ConcurrentDequeList_locked(list_) \
((ConcurrentDequeList*)((uintptr_t)(list_) | (uintptr_t)1))
/* Attempt to atomically replace the list pointer on the given deque with the
* given list, and additionally set the locking bit.
*/
#define ConcurrentDeque_try_replace_locked(deque_, list_, next_list_) \
ConcurrentDeque_try_replace( \
deque_, list_, ConcurrentDequeList_locked(next_list_))
/* A platform-specific way of pausing execution, used to provide backoff while
* spinning when waiting for a lock.
*/
#ifndef WV_PAUSE
#if defined(_WIN32)
#include <windows.h>
#define WV_PAUSE() YieldProcessor() /* Windows */
#elif defined(__GNUC__) || defined(__clang__)
#if defined(__x86_64__) || defined(__i386__)
#define WV_PAUSE() __builtin_ia32_pause() /* Intel/AMD */
#elif defined(__aarch64__) || defined(__arm__)
#define WV_PAUSE() asm volatile("yield" ::: "memory") /* ARM */
#else
#define WV_PAUSE() /* Unknown */
#endif
#else
#define WV_PAUSE() /* Unknown */
#endif
#endif
/* Pause for the given number of iterations, using the WV_PAUSE macro.
*/
static inline void ConcurrentDeque_backoff_pause(unsigned int backoff) {
for (unsigned int pause = 0; pause < backoff; pause++) {
WV_PAUSE();
}
}
/* An infinite for-loop that performs exponential backoff.
*/
#define ConcurrentDeque_backoff_loop \
for (unsigned int backoff = 1;; ConcurrentDeque_backoff_pause(backoff *= 2))
/* Return a pointer to the list on the given deque with the lock bit cleared.
*/
static inline ConcurrentDequeList* ConcurrentDeque_list(
ConcurrentDequeObject* self) {
ConcurrentDequeList* ptr = _Py_atomic_load_ptr(&self->list);
return (ConcurrentDequeList*)((uintptr_t)ptr & ~(uintptr_t)1);
}
/* Atomically replace the deque's list with a NULL list and then go about
* clearing references and freeing the list.
*/
static int ConcurrentDeque_clear(ConcurrentDequeObject* self) {
ConcurrentDeque_backoff_loop {
ConcurrentDequeList* list = ConcurrentDeque_list(self);
if (list == NULL) {
return 0;
}
if (ConcurrentDeque_try_replace(self, &list, NULL)) {
ConcurrentDequeList_dealloc(list);
return 0;
}
}
}
/* Provide the traverse implementation for the GC. Visit each node in the linked
* list if a list has been allocated.
*/
static int ConcurrentDeque_traverse(
ConcurrentDequeObject* self,
visitproc visit,
void* arg) {
ConcurrentDequeList* list = ConcurrentDeque_list(self);
if (list == NULL) {
return 0;
}
for (ConcurrentDequeNode* node = list->head; node != NULL;
node = node->next) {
Py_VISIT(node->datum);
}
return 0;
}
/* Allocate a new ConcurrentDeque and set all of its fields to their default
* values.
*/
static PyObject*
ConcurrentDeque_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
ConcurrentDequeObject* deque =
(ConcurrentDequeObject*)type->tp_alloc(type, 0);
if (deque == NULL) {
return NULL;
}
deque->list = NULL;
deque->weakreflist = NULL;
return (PyObject*)deque;
}
PyDoc_STRVAR(
ConcurrentDeque_init__doc__,
"ConcurrentDeque([iterable])\n"
"--\n"
"\n"
"A list-like sequence optimized for data accesses near its endpoints.");
static PyObject* ConcurrentDeque_extend(
ConcurrentDequeObject* self,
PyObject* iterable);
/* Initialize a new ConcurrentDeque.
*/
static int
ConcurrentDeque_init(PyObject* self, PyObject* args, PyObject* kwds) {
if (PyTuple_GET_SIZE(args) > 1) {
PyErr_SetString(
PyExc_TypeError, "ConcurrentDeque() takes zero or one argument");
return -1;
}
if (PyTuple_GET_SIZE(args) == 1) {
PyObject* arg = PyTuple_GET_ITEM(args, 0);
PyObject* result =
ConcurrentDeque_extend((ConcurrentDequeObject*)self, arg);
if (result == NULL) {
return -1;
}
Py_DECREF(result);
}
return 0;
}
/* Deallocate a ConcurrentDeque and remove any references.
*/
static void ConcurrentDeque_dealloc(ConcurrentDequeObject* self) {
PyTypeObject* tp = Py_TYPE(self);
PyObject_GC_UnTrack(self);
if (self->weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*)self);
}
ConcurrentDeque_clear(self);
tp->tp_free(self);
}
PyDoc_STRVAR(
ConcurrentDeque_append__doc__,
"append($self, item, /)\n"
"--\n"
"\n"
"Add an element to the right side of the deque.");
/* Append an item to the right side of the deque.
*/
static PyObject* ConcurrentDeque_append(
ConcurrentDequeObject* self,
PyObject* datum) {
ConcurrentDequeNode* next_node = ConcurrentDequeNode_alloc(datum, NULL, NULL);
if (next_node == NULL) {
return NULL;
}
ConcurrentDequeList* next_list =
ConcurrentDequeList_alloc(next_node, next_node);
if (next_list == NULL) {
ConcurrentDequeNode_dealloc(next_node);
return NULL;
}
ConcurrentDequeList* next_list_locked = ConcurrentDequeList_locked(next_list);
ConcurrentDeque_backoff_loop {
ConcurrentDequeList* list = ConcurrentDeque_list(self);
if (list == NULL) {
/* If the list is currently NULL, then we will attempt to replace it with
* a new list.
*/
if (ConcurrentDeque_try_replace(self, &list, next_list)) {
Py_RETURN_NONE;
}
} else if (ConcurrentDeque_try_replace(self, &list, next_list_locked)) {
/* Otherwise, we will attempt to append the item to the end of the current
* list by replacing the tail of the current list.
*/
next_list->head = list->head;
next_node->prev = list->tail;
next_node->prev->next = next_node;
ConcurrentDeque_replace(self, next_list);
ConcurrentDequeList_dealloc_shallow(list);
Py_RETURN_NONE;
}
}
}
PyDoc_STRVAR(
ConcurrentDeque_appendleft__doc__,
"appendleft($self, item, /)\n"
"--\n"
"\n"
"Add an element to the left side of the deque.");
/* Append an item to the left side of the deque.
*/
static PyObject* ConcurrentDeque_appendleft(
ConcurrentDequeObject* self,
PyObject* datum) {
ConcurrentDequeNode* next_node = ConcurrentDequeNode_alloc(datum, NULL, NULL);
if (next_node == NULL) {
return NULL;
}
ConcurrentDequeList* next_list =
ConcurrentDequeList_alloc(next_node, next_node);
if (next_list == NULL) {
ConcurrentDequeNode_dealloc(next_node);
return NULL;
}
ConcurrentDequeList* next_list_locked = ConcurrentDequeList_locked(next_list);
ConcurrentDeque_backoff_loop {
ConcurrentDequeList* list = ConcurrentDeque_list(self);
if (list == NULL) {
/* If the list is currently NULL, then we will attempt to replace it with
* a new list.
*/
if (ConcurrentDeque_try_replace(self, &list, next_list)) {
Py_RETURN_NONE;
}
} else if (ConcurrentDeque_try_replace(self, &list, next_list_locked)) {
/* Otherwise, we will attempt to append the item to the start of the
* current list by replacing the head of the current list.
*/
next_list->tail = list->tail;
next_node->next = list->head;
next_node->next->prev = next_node;
ConcurrentDeque_replace(self, next_list);
ConcurrentDequeList_dealloc_shallow(list);
Py_RETURN_NONE;
}
}
}
PyDoc_STRVAR(