concurrent-shm 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/AUTHORS +7 -0
- data/CHANGELOG.md +5 -0
- data/LICENSE +201 -0
- data/README.md +64 -0
- data/ext/concurrent-shm/extconf.rb +22 -0
- data/ext/concurrent-shm/main.c +15 -0
- data/ext/concurrent-shm/main.h +72 -0
- data/ext/concurrent-shm/posix.c +813 -0
- data/ext/concurrent-shm/types.c +180 -0
- data/ext/concurrent-shm/varargs.h +71 -0
- data/lib/concurrent-shm.rb +4 -0
- data/lib/concurrent-shm/channel.rb +524 -0
- data/lib/concurrent-shm/gem.rb +26 -0
- data/lib/concurrent-shm/int_ptr.rb +53 -0
- metadata +58 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: '097530275a20b247f31b8e8b7e69b160557e54fafdcfdf80d513c259885cba4f'
|
4
|
+
data.tar.gz: 2e651c24c8c98ff0da62b9b8f508d953dc02fb83e3f3eb05e6cf95632191e161
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: c38e9c8dfbc4960c14267fdb5ffe22c7eb3f3888cc412de71279dfd3170ed766d81129d5858fc0ff4ca06bca929ab901f8e678f6431869a0aeaa746a4e039572
|
7
|
+
data.tar.gz: 96ebe4001a346f4ec8dbc1c52e5130197ed7a28aaf8ec7d0bf842c18d5fecf36ca19a7438936b19d2cd1a537bfa61acdd0a5088318dbf4f9081c80f8519de409
|
data/AUTHORS
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
# This is the list of concurrent-shm authors for copyright purposes.
|
2
|
+
#
|
3
|
+
# This does not necessarily list everyone who has contributed code, since in
|
4
|
+
# some cases, their employer may be the copyright holder. To see the full list
|
5
|
+
# of contributors, see the revision history in source control.
|
6
|
+
|
7
|
+
Ethan Reesor
|
data/CHANGELOG.md
ADDED
data/LICENSE
ADDED
@@ -0,0 +1,201 @@
|
|
1
|
+
Apache License
|
2
|
+
Version 2.0, January 2004
|
3
|
+
http://www.apache.org/licenses/
|
4
|
+
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
6
|
+
|
7
|
+
1. Definitions.
|
8
|
+
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
11
|
+
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
13
|
+
the copyright owner that is granting the License.
|
14
|
+
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
16
|
+
other entities that control, are controlled by, or are under common
|
17
|
+
control with that entity. For the purposes of this definition,
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
19
|
+
direction or management of such entity, whether by contract or
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
22
|
+
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
24
|
+
exercising permissions granted by this License.
|
25
|
+
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
27
|
+
including but not limited to software source code, documentation
|
28
|
+
source, and configuration files.
|
29
|
+
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
31
|
+
transformation or translation of a Source form, including but
|
32
|
+
not limited to compiled object code, generated documentation,
|
33
|
+
and conversions to other media types.
|
34
|
+
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
36
|
+
Object form, made available under the License, as indicated by a
|
37
|
+
copyright notice that is included in or attached to the work
|
38
|
+
(an example is provided in the Appendix below).
|
39
|
+
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
46
|
+
the Work and Derivative Works thereof.
|
47
|
+
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
49
|
+
the original version of the Work and any modifications or additions
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
61
|
+
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
64
|
+
subsequently incorporated within the Work.
|
65
|
+
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
72
|
+
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
78
|
+
where such license applies only to those patent claims licensable
|
79
|
+
by such Contributor that are necessarily infringed by their
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
82
|
+
institute patent litigation against any entity (including a
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
85
|
+
or contributory patent infringement, then any patent licenses
|
86
|
+
granted to You under this License for that Work shall terminate
|
87
|
+
as of the date such litigation is filed.
|
88
|
+
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
91
|
+
modifications, and in Source or Object form, provided that You
|
92
|
+
meet the following conditions:
|
93
|
+
|
94
|
+
(a) You must give any other recipients of the Work or
|
95
|
+
Derivative Works a copy of this License; and
|
96
|
+
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
98
|
+
stating that You changed the files; and
|
99
|
+
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
102
|
+
attribution notices from the Source form of the Work,
|
103
|
+
excluding those notices that do not pertain to any part of
|
104
|
+
the Derivative Works; and
|
105
|
+
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
108
|
+
include a readable copy of the attribution notices contained
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
111
|
+
of the following places: within a NOTICE text file distributed
|
112
|
+
as part of the Derivative Works; within the Source form or
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
114
|
+
within a display generated by the Derivative Works, if and
|
115
|
+
wherever such third-party notices normally appear. The contents
|
116
|
+
of the NOTICE file are for informational purposes only and
|
117
|
+
do not modify the License. You may add Your own attribution
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
120
|
+
that such additional attribution notices cannot be construed
|
121
|
+
as modifying the License.
|
122
|
+
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
124
|
+
may provide additional or different license terms and conditions
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
128
|
+
the conditions stated in this License.
|
129
|
+
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
133
|
+
this License, without any additional terms or conditions.
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
135
|
+
the terms of any separate license agreement you may have executed
|
136
|
+
with Licensor regarding such Contributions.
|
137
|
+
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
140
|
+
except as required for reasonable and customary use in describing the
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
142
|
+
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
152
|
+
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
158
|
+
incidental, or consequential damages of any character arising as a
|
159
|
+
result of this License or out of the use or inability to use the
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
162
|
+
other commercial damages or losses), even if such Contributor
|
163
|
+
has been advised of the possibility of such damages.
|
164
|
+
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
168
|
+
or other liability obligations and/or rights consistent with this
|
169
|
+
License. However, in accepting such obligations, You may act only
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
174
|
+
of your accepting any such warranty or additional liability.
|
175
|
+
|
176
|
+
END OF TERMS AND CONDITIONS
|
177
|
+
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
179
|
+
|
180
|
+
To apply the Apache License to your work, attach the following
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
182
|
+
replaced with your own identifying information. (Don't include
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
184
|
+
comment syntax for the file format. We also recommend that a
|
185
|
+
file or class name and description of purpose be included on the
|
186
|
+
same "printed page" as the copyright notice for easier
|
187
|
+
identification within third-party archives.
|
188
|
+
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
190
|
+
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
192
|
+
you may not use this file except in compliance with the License.
|
193
|
+
You may obtain a copy of the License at
|
194
|
+
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
196
|
+
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
200
|
+
See the License for the specific language governing permissions and
|
201
|
+
limitations under the License.
|
data/README.md
ADDED
@@ -0,0 +1,64 @@
|
|
1
|
+
# Concurrent Shared Memory
|
2
|
+
|
3
|
+
## OS-specific details
|
4
|
+
|
5
|
+
### Windows
|
6
|
+
|
7
|
+
**Not supported (will not compile).**
|
8
|
+
|
9
|
+
### MacOS
|
10
|
+
|
11
|
+
- `SharedMemory#size=` can only be called once per object.
|
12
|
+
- `SharedMemory#size=(n)` rounds up to the nearest multiple of the system page size (usually 4KiB).
|
13
|
+
- `Region.map` will raise `Errno::EINVAL` if the shared memory object is not large enough.
|
14
|
+
|
15
|
+
### Linux
|
16
|
+
|
17
|
+
- `SharedMemory#size=` can be called more than once per object.
|
18
|
+
- `SharedMemory#size=(n)` will not round, and `#size` will report the value set.
|
19
|
+
- `Region.map` will succeed regardless of the shared memory object's size, but
|
20
|
+
calling `Region#read` or `Region#write` will cause a bus error (and crash the
|
21
|
+
program) if the read/write is out of bounds of the shared memory object.
|
22
|
+
|
23
|
+
## WARNING
|
24
|
+
|
25
|
+
This library does not guarentee memory safety - it assumes you know what you're
|
26
|
+
doing. If you are uncomfortable using the underlying constructs directly, you
|
27
|
+
probably shouldn't use this library. If you're not careful, things will go
|
28
|
+
wrong.
|
29
|
+
|
30
|
+
1. Never allocate multiple objects using the same or overlapping regions of the
|
31
|
+
same shared memory space. The library will not stop you, but doing this will
|
32
|
+
likely cause memory faults.
|
33
|
+
1. Avoid using `Region#as_*ptr` methods. The returned pointer objects do not
|
34
|
+
retain a reference to the region. If the region is garbage collected, it will
|
35
|
+
be unmapped, and subsequent pointer accesses will likely cause memory faults.
|
36
|
+
|
37
|
+
```ruby
|
38
|
+
shm = ConcurrentSHM::SharedMemory.open("/foo/bar", 0600, mode: :anon)
|
39
|
+
value = ConcurrentSHM::Region.map(shm, 0, 1).as_intptr
|
40
|
+
GC.start
|
41
|
+
value.read # => memory fault
|
42
|
+
```
|
43
|
+
|
44
|
+
In the above example, `value.read` will likely cause a crash - if the region
|
45
|
+
`value` was created from has been garbage collected, `value` will point to
|
46
|
+
unmapped memory, since regions are unmapped once they are collected.
|
47
|
+
|
48
|
+
## Examples
|
49
|
+
|
50
|
+
```ruby
|
51
|
+
shm = ConcurrentSHM::SharedMemory.open("/foo/bar", 0600, mode: :anon)
|
52
|
+
ch = ConcurrentSHM::Channel::SingleBuffered::Variable.new(shm, capacity: 200)
|
53
|
+
|
54
|
+
fork do
|
55
|
+
loop do
|
56
|
+
s = ch.recv
|
57
|
+
puts "received! #{s.inspect}"
|
58
|
+
end
|
59
|
+
end
|
60
|
+
|
61
|
+
STDIN.each_line do |l|
|
62
|
+
ch.send(l)
|
63
|
+
end
|
64
|
+
```
|
@@ -0,0 +1,22 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'mkmf'
|
4
|
+
|
5
|
+
fns = %w(shm_open shm_unlink fstat ftruncate mmap munmap)
|
6
|
+
fns += %w(pthread_mutexattr_init pthread_mutexattr_setpshared pthread_mutex_init pthread_mutexattr_destroy pthread_mutex_destroy)
|
7
|
+
fns += %w(pthread_condattr_init pthread_condattr_setpshared pthread_cond_init pthread_condattr_destroy pthread_cond_destroy)
|
8
|
+
fns += %w(pthread_mutex_lock pthread_mutex_trylock pthread_mutex_unlock pthread_cond_signal pthread_cond_broadcast pthread_cond_wait pthread_cond_timedwait)
|
9
|
+
fns.each { |fn| abort "missing #{fn}" unless have_func fn }
|
10
|
+
|
11
|
+
warn = RbConfig::MAKEFILE_CONFIG['warnflags'].split(' ')
|
12
|
+
warn -= ['-Wdeclaration-after-statement', '-Wtype-limits'] # things I don't care about
|
13
|
+
warn += ['-Wno-type-limits']
|
14
|
+
warn -= ['-Wno-self-assign', '-Wno-parentheses-equality', '-Wno-constant-logical-operand', '-Wno-cast-function-type'] # "unrecognized command line option"
|
15
|
+
$warnflags = warn.join(' ')
|
16
|
+
|
17
|
+
RbConfig::MAKEFILE_CONFIG['CC'] = ENV['CC'] if ENV['CC']
|
18
|
+
|
19
|
+
RbConfig::MAKEFILE_CONFIG['CFLAGS'] << ' -gdwarf-2 -g3 -O0' if ENV['debug']
|
20
|
+
|
21
|
+
dir_config('ruby')
|
22
|
+
with_cflags(RbConfig::MAKEFILE_CONFIG['CFLAGS']) { create_makefile('concurrent-shm/cshm') }
|
@@ -0,0 +1,15 @@
|
|
1
|
+
#include "main.h"
|
2
|
+
|
3
|
+
void Init_PtrTypes(VALUE ns, VALUE base);
|
4
|
+
void Init_posix(VALUE ConcurrentSHM);
|
5
|
+
|
6
|
+
void Init_cshm()
|
7
|
+
{
|
8
|
+
VALUE ConcurrentSHM = rb_define_module("ConcurrentSHM");
|
9
|
+
|
10
|
+
Init_posix(ConcurrentSHM);
|
11
|
+
|
12
|
+
VALUE Value = rb_define_module_under(ConcurrentSHM, "Value");
|
13
|
+
VALUE IntPtr = rb_define_class_under(Value, "IntPtr", rb_cObject);
|
14
|
+
Init_PtrTypes(Value, IntPtr);
|
15
|
+
}
|
@@ -0,0 +1,72 @@
|
|
1
|
+
#include <ruby.h>
|
2
|
+
|
3
|
+
/* To prevent unused parameter warnings */
|
4
|
+
#define UNUSED(x) (void)(x)
|
5
|
+
|
6
|
+
// __shared_retain -> increments and returns new value
|
7
|
+
// __shared_release -> decrements and returns new value
|
8
|
+
|
9
|
+
#ifdef __APPLE__
|
10
|
+
#include <Availability.h>
|
11
|
+
#if defined(__MAC_10_12) && __MAC_OS_X_VERSION_MAX_ALLOWED >= __MAC_10_12
|
12
|
+
#include <stdatomic.h>
|
13
|
+
#define __shared_retain(ptr) (atomic_fetch_add_explicit(ptr, 1, memory_order_acquire) + 1)
|
14
|
+
#define __shared_release(ptr) (atomic_fetch_sub_explicit(ptr, 1, memory_order_release) - 1)
|
15
|
+
typedef atomic_uint_fast32_t refcount;
|
16
|
+
#else
|
17
|
+
#include <libkern/OSAtomic.h>
|
18
|
+
#define __shared_retain(ptr) OSAtomicIncrement32Barrier(ptr)
|
19
|
+
#define __shared_release(ptr) OSAtomicDecrement32Barrier(ptr)
|
20
|
+
typedef uint32_t refcount;
|
21
|
+
#endif
|
22
|
+
#else
|
23
|
+
#define __shared_retain(ptr) __sync_add_and_fetch(ptr, 1)
|
24
|
+
#define __shared_release(ptr) __sync_sub_and_fetch(ptr, 1)
|
25
|
+
typedef uint32_t refcount;
|
26
|
+
#endif
|
27
|
+
|
28
|
+
#define debug(n, fmt, ...) \
|
29
|
+
do { \
|
30
|
+
VALUE args[] = {rb_str_new_cstr(fmt), ##__VA_ARGS__}; \
|
31
|
+
rb_io_write(rb_stdout, rb_f_sprintf(n+1, args)); \
|
32
|
+
} while(0);
|
33
|
+
|
34
|
+
#define rb_syserr_fail_strf(err, format, ...) rb_syserr_fail_str(err, rb_sprintf(format, ##__VA_ARGS__))
|
35
|
+
#define rb_check_syserr_fail_strf(r, err, format, ...) \
|
36
|
+
do { \
|
37
|
+
if (r) { \
|
38
|
+
rb_syserr_fail_str(err, rb_sprintf(format, ##__VA_ARGS__)); \
|
39
|
+
} \
|
40
|
+
} while (0)
|
41
|
+
|
42
|
+
#define chk_err(fn, args, format, ...) \
|
43
|
+
do { \
|
44
|
+
int err = fn args; \
|
45
|
+
rb_check_syserr_fail_strf(err, err, #fn "(" format ")", ##__VA_ARGS__); \
|
46
|
+
} while (0)
|
47
|
+
|
48
|
+
#define chk_errno(fn, args, format, ...) \
|
49
|
+
rb_check_syserr_fail_strf(fn args, errno, #fn "(" format ")", ##__VA_ARGS__)
|
50
|
+
|
51
|
+
#define PtrTypes \
|
52
|
+
X(Int8, int8, __value2int, 8); \
|
53
|
+
X(Int16, int16, __value2int, 16); \
|
54
|
+
X(Int32, int32, __value2int, 32); \
|
55
|
+
X(Int64, int64, __value2int, 64); \
|
56
|
+
X(UInt8, uint8, __value2uint, 8); \
|
57
|
+
X(UInt16, uint16, __value2uint, 16); \
|
58
|
+
X(UInt32, uint32, __value2uint, 32); \
|
59
|
+
X(UInt64, uint64, __value2uint, 64);
|
60
|
+
|
61
|
+
#define Ptr2ValueFn(rtype, ctype) VALUE rtype##Ptr2Value(ctype##_t * v)
|
62
|
+
#define Value2PtrFn(rtype, ctype) ctype##_t * Value2##rtype##Ptr(VALUE v)
|
63
|
+
|
64
|
+
#define X(r, c, ...) Ptr2ValueFn(r, c);
|
65
|
+
PtrTypes
|
66
|
+
#undef X
|
67
|
+
|
68
|
+
#define X(r, c, ...) Value2PtrFn(r, c);
|
69
|
+
PtrTypes
|
70
|
+
#undef X
|
71
|
+
|
72
|
+
void Init_PtrTypes(VALUE ns, VALUE base);
|
@@ -0,0 +1,813 @@
|
|
1
|
+
#include <errno.h>
|
2
|
+
#include <sys/mman.h>
|
3
|
+
#include <sys/stat.h>
|
4
|
+
#include <fcntl.h>
|
5
|
+
#include <pthread.h>
|
6
|
+
|
7
|
+
#include "main.h"
|
8
|
+
#include <ruby/thread.h>
|
9
|
+
#include "varargs.h"
|
10
|
+
|
11
|
+
static VALUE Finalizer, SharedMemory, Region, Mutex, Condition;
|
12
|
+
|
13
|
+
/*
|
14
|
+
* Document-class: ConcurrentSHM::SharedMemory
|
15
|
+
* A POSIX shared memory object.
|
16
|
+
*/
|
17
|
+
|
18
|
+
/* Delete a POSIX shared memory object.
|
19
|
+
* @param name [String] the name of the object
|
20
|
+
* @return [nil]
|
21
|
+
* @raise [ArgumentError] if the name is nil or is not a string
|
22
|
+
* @raise [Errno::EACCES] if permission to delete the object is denied
|
23
|
+
* @raise [Errno::ENOENT] if the named object does not exist
|
24
|
+
*/
|
25
|
+
static VALUE shared_memory_delete(VALUE self, VALUE name)
|
26
|
+
{
|
27
|
+
UNUSED(self);
|
28
|
+
|
29
|
+
if (NIL_P(name)) {
|
30
|
+
rb_raise(rb_eArgError, "Name must not be nil");
|
31
|
+
}
|
32
|
+
|
33
|
+
char * cname = StringValueCStr(name);
|
34
|
+
chk_errno(shm_unlink, (cname), "%s", cname);
|
35
|
+
|
36
|
+
return Qnil;
|
37
|
+
}
|
38
|
+
|
39
|
+
/* @overload open(name, fmode, mode: :excl)
|
40
|
+
* Create or open a POSIX shared memory object. The default flags are
|
41
|
+
* `O_CREATE`, `O_RDWR`, and `O_TRUNC`.
|
42
|
+
*
|
43
|
+
* If the mode is `:excl`, `:exclusive`, `:anon`, or `:anonymous`, the object
|
44
|
+
* is opened exclusively, with the `O_EXCL` flag in addition to the defaults.
|
45
|
+
*
|
46
|
+
* If the mode is `:anon` or `:anonymous`, the object is deleted immediately
|
47
|
+
* after being opened. Opened and deleted shared memory objects can be used
|
48
|
+
* until the object is closed.
|
49
|
+
*
|
50
|
+
* If the mode is `:shared`, the object is opened with the default flags.
|
51
|
+
*
|
52
|
+
* @param name [String] the name of the object
|
53
|
+
* @param fmode [Integer] the file mode of the object
|
54
|
+
* @param mode [Symbol] the manner in which to create or open the object.
|
55
|
+
* @return [SharedMemory] the shared memory object
|
56
|
+
* @raise [ArgumentError] if the name is nil or is not a string
|
57
|
+
* @raise [Errno::EACCES] if permission to create or open the object is denied
|
58
|
+
* @raise [Errno::EEXIST] if `exclusive` is `true` and the object specified by `name` already exists
|
59
|
+
* @raise [Errno::EINVAL] if the name is invalid
|
60
|
+
* @raise [Errno::EMFILE] if the per-process limit on the number of open file descriptors has been reached
|
61
|
+
* @raise [Errno::ENAMETOOLONG] if the name is too long
|
62
|
+
* @raise [Errno::ENFILE] if the system-wide limit on the total number of open files has been reached
|
63
|
+
*/
|
64
|
+
static VALUE shared_memory_open(int argc, VALUE * argv, VALUE self)
|
65
|
+
{
|
66
|
+
CONST_IDS(id_, exclusive, anonymous, shared, excl, anon);
|
67
|
+
|
68
|
+
VALUE name, fmode;
|
69
|
+
KWARGS(ARGS("2:", name, fmode), 0, mode);
|
70
|
+
|
71
|
+
if (NIL_P(name)) {
|
72
|
+
rb_raise(rb_eArgError, "Name must not be nil");
|
73
|
+
}
|
74
|
+
|
75
|
+
ID id_mode = mode == Qundef ? id_excl : SYM2ID(mode);
|
76
|
+
char * cname = StringValueCStr(name);
|
77
|
+
int oflag = O_CREAT | O_RDWR | O_TRUNC | (id_mode == id_shared ? 0 : O_EXCL);
|
78
|
+
int fd = shm_open(cname, oflag, FIX2INT(fmode));
|
79
|
+
if (fd < 0) {
|
80
|
+
int err = errno;
|
81
|
+
if (err != EMFILE && err != ENFILE && err != ENOMEM) {
|
82
|
+
rb_syserr_fail_strf(err, "shm_open(%s, %d, %d)", cname, oflag, FIX2INT(fmode));
|
83
|
+
}
|
84
|
+
|
85
|
+
// if ERRNO indicates no memory, GC and try again
|
86
|
+
rb_gc();
|
87
|
+
fd = shm_open(cname, oflag, FIX2INT(fmode));
|
88
|
+
rb_check_syserr_fail_strf(fd < 0, errno, "shm_open(%s, %d, %d)", cname, oflag, FIX2INT(fmode));
|
89
|
+
}
|
90
|
+
|
91
|
+
if (id_mode == id_anon || id_mode == id_anonymous) {
|
92
|
+
shared_memory_delete(self, name);
|
93
|
+
}
|
94
|
+
|
95
|
+
return rb_funcall(self, rb_intern("new"), 2, INT2FIX(fd), name);
|
96
|
+
}
|
97
|
+
|
98
|
+
/* Create a {SharedMemory} instance for the specified file descriptor.
|
99
|
+
* @param fd [Integer] the file descriptor
|
100
|
+
* @param name [String] the name
|
101
|
+
*/
|
102
|
+
static VALUE shared_memory_initialize(VALUE self, VALUE fd, VALUE name)
|
103
|
+
{
|
104
|
+
rb_call_super(1, &fd); // super(fd)
|
105
|
+
rb_iv_set(self, "@name", name); // @name = name
|
106
|
+
return self;
|
107
|
+
}
|
108
|
+
|
109
|
+
/* The size of the shared memory space using `fstat`.
|
110
|
+
* @return [Integer]
|
111
|
+
* @raise [Errno::EBADF] if the receivers `fileno` is not a valid file descriptor
|
112
|
+
*/
|
113
|
+
static VALUE shared_memory_size(VALUE self)
|
114
|
+
{
|
115
|
+
struct stat stat;
|
116
|
+
VALUE fd = rb_funcall(self, rb_intern("fileno"), 0);
|
117
|
+
chk_err(fstat, (FIX2INT(fd), &stat), "fd=%d", FIX2INT(fd));
|
118
|
+
return INT2FIX(stat.st_size);
|
119
|
+
}
|
120
|
+
|
121
|
+
/* Set the size of the shared memory space using `ftruncate`.
|
122
|
+
* @param size [Integer] the new size of the space
|
123
|
+
*/
|
124
|
+
static VALUE shared_memory_size_eq(VALUE self, VALUE size)
|
125
|
+
{
|
126
|
+
VALUE fd = rb_funcall(self, rb_intern("fileno"), 0);
|
127
|
+
chk_errno(ftruncate, (FIX2INT(fd), FIX2INT(size)), "%d, %d", FIX2INT(fd), FIX2INT(size));
|
128
|
+
return size;
|
129
|
+
}
|
130
|
+
|
131
|
+
typedef struct region {
|
132
|
+
void * data;
|
133
|
+
size_t len;
|
134
|
+
char mapped;
|
135
|
+
VALUE from;
|
136
|
+
} region_t;
|
137
|
+
|
138
|
+
struct mutex_shared {
|
139
|
+
pthread_mutexattr_t attr;
|
140
|
+
pthread_mutex_t mu;
|
141
|
+
refcount refcount;
|
142
|
+
};
|
143
|
+
|
144
|
+
typedef struct mutex {
|
145
|
+
VALUE region;
|
146
|
+
struct mutex_shared * shared;
|
147
|
+
} mutex_t;
|
148
|
+
|
149
|
+
struct condition_shared {
|
150
|
+
pthread_condattr_t attr;
|
151
|
+
pthread_cond_t cond;
|
152
|
+
refcount refcount;
|
153
|
+
};
|
154
|
+
|
155
|
+
typedef struct condition {
|
156
|
+
VALUE region;
|
157
|
+
struct condition_shared * shared;
|
158
|
+
} condition_t;
|
159
|
+
|
160
|
+
typedef struct finalizer {
|
161
|
+
VALUE class;
|
162
|
+
union {
|
163
|
+
void * raw;
|
164
|
+
region_t * region;
|
165
|
+
mutex_t * mutex;
|
166
|
+
condition_t * condition;
|
167
|
+
} as;
|
168
|
+
} finalizer_t;
|
169
|
+
|
170
|
+
static void __region_mark(region_t * r)
|
171
|
+
{
|
172
|
+
rb_gc_mark(r->from);
|
173
|
+
}
|
174
|
+
|
175
|
+
static void __mutex_mark(mutex_t * mu)
|
176
|
+
{
|
177
|
+
rb_gc_mark(mu->region);
|
178
|
+
}
|
179
|
+
|
180
|
+
static void __condition_mark(condition_t * cond)
|
181
|
+
{
|
182
|
+
rb_gc_mark(cond->region);
|
183
|
+
}
|
184
|
+
|
185
|
+
static void __finalizer_mark(finalizer_t * fin)
|
186
|
+
{
|
187
|
+
rb_gc_mark(fin->class);
|
188
|
+
}
|
189
|
+
|
190
|
+
#define StructTypes \
|
191
|
+
X(region); \
|
192
|
+
X(mutex); \
|
193
|
+
X(condition); \
|
194
|
+
X(finalizer);
|
195
|
+
|
196
|
+
#define X(type, ...) static int __##type##_size(const type##_t * x) { return sizeof(type##_t); }
|
197
|
+
StructTypes
|
198
|
+
#undef X
|
199
|
+
|
200
|
+
#define X(type, ...) \
|
201
|
+
static const rb_data_type_t __##type##_rb_type = { \
|
202
|
+
.wrap_struct_name = #type "_t", \
|
203
|
+
.function = { \
|
204
|
+
.dmark = (void (*)(void*))__##type##_mark, \
|
205
|
+
.dfree = RUBY_TYPED_DEFAULT_FREE, \
|
206
|
+
.dsize = (size_t (*)(const void*))__##type##_size, \
|
207
|
+
}, \
|
208
|
+
};
|
209
|
+
StructTypes
|
210
|
+
#undef X
|
211
|
+
|
212
|
+
#define X(type, ...) \
|
213
|
+
static inline type##_t * value_as_##type(VALUE self) { \
|
214
|
+
type##_t * x; \
|
215
|
+
TypedData_Get_Struct(self, type##_t, &__##type##_rb_type, x); \
|
216
|
+
return x; \
|
217
|
+
}
|
218
|
+
StructTypes
|
219
|
+
#undef X
|
220
|
+
|
221
|
+
#define X(type, ...) \
|
222
|
+
static VALUE __##type##_alloc(VALUE self) \
|
223
|
+
{ \
|
224
|
+
type##_t * x; \
|
225
|
+
VALUE obj = TypedData_Make_Struct(self, type##_t, &__##type##_rb_type, x); \
|
226
|
+
return obj; \
|
227
|
+
}
|
228
|
+
StructTypes
|
229
|
+
#undef X
|
230
|
+
|
231
|
+
/*
|
232
|
+
* Document-class: ConcurrentSHM::Finalizer
|
233
|
+
* @!visibility private
|
234
|
+
*/
|
235
|
+
|
236
|
+
static void __set_finalizer(VALUE obj, void * data)
|
237
|
+
{
|
238
|
+
VALUE fin = __finalizer_alloc(Finalizer);
|
239
|
+
finalizer_t * f = value_as_finalizer(fin);
|
240
|
+
f->class = rb_class_of(obj);
|
241
|
+
f->as.raw = data;
|
242
|
+
|
243
|
+
rb_define_finalizer(obj, fin);
|
244
|
+
}
|
245
|
+
|
246
|
+
/*
|
247
|
+
* @!visibility private
|
248
|
+
*/
|
249
|
+
static VALUE __finalize(VALUE blk, VALUE objid)
|
250
|
+
{
|
251
|
+
finalizer_t * f = (finalizer_t *)rb_data_object_get(blk);
|
252
|
+
|
253
|
+
if (f->class == Region) {
|
254
|
+
if (f->as.region->mapped && f->as.region->data) {
|
255
|
+
if (munmap(f->as.region->data, f->as.region->len)) {
|
256
|
+
perror("munmap");
|
257
|
+
}
|
258
|
+
f->as.region->data = NULL;
|
259
|
+
}
|
260
|
+
|
261
|
+
} else if (f->class == Mutex) {
|
262
|
+
if (f->as.mutex->shared && __shared_release(&f->as.mutex->shared->refcount) == 0) {
|
263
|
+
if (pthread_mutexattr_destroy(&f->as.mutex->shared->attr)) {
|
264
|
+
perror("pthread_mutexattr_destroy");
|
265
|
+
}
|
266
|
+
if (pthread_mutex_destroy(&f->as.mutex->shared->mu)) {
|
267
|
+
perror("pthread_mutex_destroy");
|
268
|
+
}
|
269
|
+
f->as.mutex->shared = NULL;
|
270
|
+
}
|
271
|
+
|
272
|
+
} else if (f->class == Condition) {
|
273
|
+
if (f->as.condition->shared && __shared_release(&f->as.condition->shared->refcount) == 0) {
|
274
|
+
if (pthread_condattr_destroy(&f->as.condition->shared->attr)) {
|
275
|
+
perror("pthread_condattr_destroy");
|
276
|
+
}
|
277
|
+
if (pthread_cond_destroy(&f->as.condition->shared->cond)) {
|
278
|
+
perror("pthread_cond_destroy");
|
279
|
+
}
|
280
|
+
f->as.condition->shared = NULL;
|
281
|
+
}
|
282
|
+
}
|
283
|
+
|
284
|
+
return Qnil;
|
285
|
+
}
|
286
|
+
|
287
|
+
/*
|
288
|
+
* Document-class: ConcurrentSHM::Region
|
289
|
+
* A memory-mapped region of a file or shared memory space.
|
290
|
+
*/
|
291
|
+
|
292
|
+
static VALUE __new_region(void * data, size_t len, char mapped, VALUE from)
|
293
|
+
{
|
294
|
+
VALUE self = __region_alloc(Region);
|
295
|
+
region_t * r = value_as_region(self);
|
296
|
+
r->data = data;
|
297
|
+
r->len = len;
|
298
|
+
r->mapped = mapped;
|
299
|
+
r->from = from;
|
300
|
+
|
301
|
+
if (mapped) {
|
302
|
+
__set_finalizer(self, r);
|
303
|
+
}
|
304
|
+
return self;
|
305
|
+
}
|
306
|
+
|
307
|
+
static VALUE __region_from(void * data, size_t len, VALUE from)
|
308
|
+
{
|
309
|
+
return __new_region(data, len, 0, from);
|
310
|
+
}
|
311
|
+
|
312
|
+
/* Memory-map a region of a file or shared memory space. The region is
|
313
|
+
* read/write and shared.
|
314
|
+
* @param file [IO|SharedMemory] the file or shared memory space
|
315
|
+
* @param off [Integer] the offset of the region
|
316
|
+
* @param len [Integer] the length of the region
|
317
|
+
* @return [Region] the mapped region
|
318
|
+
* @raise [Errno::EACCES] if the file is not a regular file, or the file is not
|
319
|
+
* open for reading, not open for writing, or append-only
|
320
|
+
* @raise [Errno::EAGAIN] if the file is locked or too much memory has been locked
|
321
|
+
* @raise [Errno::EBADF] if `file.lineno` is not a valid file descriptor
|
322
|
+
* @raise [Errno::EINVAL] if the length or offset are too large or the length is 0
|
323
|
+
* @raise [Errno::ENFILE] if the system-wide limit on the total number of open files has been reached
|
324
|
+
* @raise [Errno::ENODEV] if the underlying filesystem of the specified file does not support memory mapping
|
325
|
+
* @raise [Errno::ENOMEM] if no memory is available, or the process's number of mappings limit has been reached
|
326
|
+
* @raise [Errno::EPERM] if the operation was prevented by a file seal
|
327
|
+
*/
|
328
|
+
static VALUE region_map(VALUE self, VALUE file, VALUE off, VALUE len)
|
329
|
+
{
|
330
|
+
UNUSED(self);
|
331
|
+
|
332
|
+
int fd = FIX2INT(rb_funcall(file, rb_intern("fileno"), 0));
|
333
|
+
void * data = mmap(NULL, FIX2INT(len), PROT_READ | PROT_WRITE, MAP_SHARED, fd, FIX2INT(off));
|
334
|
+
if (data == MAP_FAILED) {
|
335
|
+
rb_syserr_fail_strf(errno, "mmap(fd=%d, len=%d)", fd, FIX2INT(len));
|
336
|
+
}
|
337
|
+
|
338
|
+
return __new_region(data, FIX2INT(len), 1, file);
|
339
|
+
}
|
340
|
+
|
341
|
+
/* Unmaps a memory-mapped region.
|
342
|
+
* @param region [Region] the region to unmap
|
343
|
+
*/
|
344
|
+
static VALUE region_unmap(VALUE self, VALUE region)
|
345
|
+
{
|
346
|
+
UNUSED(self);
|
347
|
+
|
348
|
+
region_t * r = value_as_region(region);
|
349
|
+
if (!r->mapped) {
|
350
|
+
rb_raise(rb_eArgError, "Not a memory mapped region");
|
351
|
+
}
|
352
|
+
|
353
|
+
if (!r->data) {
|
354
|
+
return Qnil;
|
355
|
+
}
|
356
|
+
|
357
|
+
chk_errno(munmap, (r->data, r->len), "");
|
358
|
+
|
359
|
+
r->data = NULL;
|
360
|
+
r->len = 0;
|
361
|
+
return Qnil;
|
362
|
+
}
|
363
|
+
|
364
|
+
static VALUE __region_at_len(VALUE self, off_t off, size_t len)
|
365
|
+
{
|
366
|
+
region_t * r = value_as_region(self);
|
367
|
+
if (off < 0) {
|
368
|
+
rb_raise(rb_eRangeError, "Out of range: offset is negative");
|
369
|
+
} else if (len < 0) {
|
370
|
+
rb_raise(rb_eRangeError, "Out of range: length is negative");
|
371
|
+
} else if (off + len > r->len) {
|
372
|
+
rb_raise(rb_eRangeError, "Out of range: offset %llu and length %llu exceeds region length %llu", (unsigned long long)off, (unsigned long long)len, (unsigned long long)r->len);
|
373
|
+
}
|
374
|
+
|
375
|
+
return __region_from((void *)((char *)r->data + off), len, self);
|
376
|
+
}
|
377
|
+
|
378
|
+
static VALUE __region_at(VALUE self, off_t begin, off_t end, VALUE exclusive)
|
379
|
+
{
|
380
|
+
return __region_at_len(self, begin, end-begin + (exclusive == Qtrue ? 0 : 1));
|
381
|
+
}
|
382
|
+
|
383
|
+
/* Get a subregion of the receiver.
|
384
|
+
* @return [Region] the subregion
|
385
|
+
* @raise ArgumentError if the arguments are not one of the allowed overloads
|
386
|
+
* @raise RangeError if the arguments do not refer to a valid subrange
|
387
|
+
*
|
388
|
+
* @overload [](start)
|
389
|
+
* The subregion from the start index to the end of the region.
|
390
|
+
* @param start [Integer] the starting index of the subset
|
391
|
+
* @raise ArgumentError unless `start` is an integer
|
392
|
+
* @overload [](start...)
|
393
|
+
* The subregion from the start index to the end of the region.
|
394
|
+
* @param start [Integer] the starting index of the subset
|
395
|
+
* @raise ArgumentError unless `start` is an integer
|
396
|
+
* @overload [](start, length)
|
397
|
+
* The subregion from the start index with the specified length.
|
398
|
+
* @param start [Integer] the starting index of the subset
|
399
|
+
* @param length [Integer] the length of the subset
|
400
|
+
* @raise ArgumentError unless `start` and `length` are integers
|
401
|
+
* @overload [](start..end)
|
402
|
+
* The subregion from the start index to the end index, inclusive.
|
403
|
+
* @param start [Integer] the starting index of the subset
|
404
|
+
* @param end [Integer] the ending index of the subset
|
405
|
+
* @raise ArgumentError unless `start` and `end` are integers
|
406
|
+
* @overload [](start...end)
|
407
|
+
* The subregion from the start index to the end index, exclusive.
|
408
|
+
* @param start [Integer] the starting index of the subset
|
409
|
+
* @param end [Integer] the ending index of the subset
|
410
|
+
* @raise ArgumentError unless `start` and `end` are integers
|
411
|
+
*/
|
412
|
+
static VALUE region_at(int argc, VALUE * argv, VALUE self)
|
413
|
+
{
|
414
|
+
VALUE at, len;
|
415
|
+
rb_scan_args(argc, argv, "11", &at, &len);
|
416
|
+
|
417
|
+
if (RB_TYPE_P(at, T_FIXNUM) && RB_TYPE_P(len, T_FIXNUM)) {
|
418
|
+
return __region_at_len(self, FIX2INT(at), FIX2INT(len));
|
419
|
+
|
420
|
+
} else if (RB_TYPE_P(at, T_FIXNUM) && NIL_P(len)) {
|
421
|
+
return __region_at_len(self, FIX2INT(at), 1);
|
422
|
+
|
423
|
+
} else if (rb_obj_is_kind_of(at, rb_cRange) && NIL_P(len)) {
|
424
|
+
// continue
|
425
|
+
|
426
|
+
} else {
|
427
|
+
rb_raise(rb_eArgError, "Region#[at, len] accepts [int,int], [int], [int...nil], or [int...int]");
|
428
|
+
}
|
429
|
+
|
430
|
+
VALUE begin = rb_funcall(at, rb_intern("begin"), 0);
|
431
|
+
VALUE end = rb_funcall(at, rb_intern("end"), 0);
|
432
|
+
VALUE excl = rb_funcall(at, rb_intern("exclude_end?"), 0);
|
433
|
+
|
434
|
+
if (!RB_TYPE_P(begin, T_FIXNUM)) {
|
435
|
+
rb_raise(rb_eArgError, "Region#[at, len] accepts [int,int], [int], [int...nil], or [int...int]");
|
436
|
+
}
|
437
|
+
|
438
|
+
if (NIL_P(end)) {
|
439
|
+
region_t * r = value_as_region(self);
|
440
|
+
return __region_at(self, FIX2INT(begin), r->len, Qtrue);
|
441
|
+
}
|
442
|
+
|
443
|
+
if (!RB_TYPE_P(end, T_FIXNUM)) {
|
444
|
+
rb_raise(rb_eArgError, "Region#[at, len] accepts [int,int], [int], [int...nil], or [int...int]");
|
445
|
+
}
|
446
|
+
|
447
|
+
return __region_at(self, FIX2INT(begin), FIX2INT(end), excl);
|
448
|
+
}
|
449
|
+
|
450
|
+
/* Returns a pointer to the region as a {Value::IntPtr signed integer pointer}
|
451
|
+
* of the same width as the region.
|
452
|
+
* @return [Value::IntPtr] the interger pointer
|
453
|
+
* @raise [RangeError] if the region is not 1, 2, 4, or 8 bytes wide
|
454
|
+
*/
|
455
|
+
static VALUE region_as_intptr(VALUE self)
|
456
|
+
{
|
457
|
+
region_t * r = value_as_region(self);
|
458
|
+
switch (r->len) {
|
459
|
+
case 1: return Int8Ptr2Value ((int8_t *) r->data);
|
460
|
+
case 2: return Int16Ptr2Value((int16_t *)r->data);
|
461
|
+
case 4: return Int32Ptr2Value((int32_t *)r->data);
|
462
|
+
case 8: return Int64Ptr2Value((int64_t *)r->data);
|
463
|
+
default: rb_raise(rb_eRangeError, "Region length must be 1, 2, 4, or 8 bytes to use as an integer pointer");
|
464
|
+
}
|
465
|
+
}
|
466
|
+
|
467
|
+
/* Returns a pointer to the region as an {Value::IntPtr unsigned integer pointer}
|
468
|
+
* of the same width as the region.
|
469
|
+
* @return [Value::IntPtr] the interger pointer
|
470
|
+
* @raise [RangeError] if the region is not 1, 2, 4, or 8 bytes wide
|
471
|
+
*/
|
472
|
+
static VALUE region_as_uintptr(VALUE self)
|
473
|
+
{
|
474
|
+
region_t * r = value_as_region(self);
|
475
|
+
switch (r->len) {
|
476
|
+
case 1: return UInt8Ptr2Value ((uint8_t *) r->data);
|
477
|
+
case 2: return UInt16Ptr2Value((uint16_t *)r->data);
|
478
|
+
case 4: return UInt32Ptr2Value((uint32_t *)r->data);
|
479
|
+
case 8: return UInt64Ptr2Value((uint64_t *)r->data);
|
480
|
+
default: rb_raise(rb_eRangeError, "Region length must be 1, 2, 4, or 8 bytes to use as an integer pointer");
|
481
|
+
}
|
482
|
+
}
|
483
|
+
|
484
|
+
#define ralign(r, b) ((uintptr_t)r->data % b)
|
485
|
+
|
486
|
+
/* The alignment of the region to the specified byte boundary. Equivalent to
|
487
|
+
* `addr % bytes`.
|
488
|
+
* @return [Integer] the region's alignment to the specified boundary
|
489
|
+
*/
|
490
|
+
static VALUE region_alignment(VALUE self, VALUE bytes)
|
491
|
+
{
|
492
|
+
region_t * r = value_as_region(self);
|
493
|
+
return INT2FIX(ralign(r, FIX2INT(bytes)));
|
494
|
+
}
|
495
|
+
|
496
|
+
/* Returns true if the region is aligned to the specified byte boundary.
|
497
|
+
* Equivalent to `addr % bytes == 0`.
|
498
|
+
* @return [Boolean] `true` if the region is aligned to the specified boundary
|
499
|
+
*/
|
500
|
+
static VALUE region_aligned_q(VALUE self, VALUE bytes)
|
501
|
+
{
|
502
|
+
region_t * r = value_as_region(self);
|
503
|
+
return ralign(r, FIX2INT(bytes)) == 0 ? Qtrue : Qfalse;
|
504
|
+
}
|
505
|
+
|
506
|
+
/* The file, shared memory space, or region the receiver was created from.
|
507
|
+
* @return [IO|SharedMemory|Region] the file, shared memory space, or region
|
508
|
+
*/
|
509
|
+
static VALUE region_from(VALUE self)
|
510
|
+
{
|
511
|
+
region_t * r = value_as_region(self);
|
512
|
+
return r->from;
|
513
|
+
}
|
514
|
+
|
515
|
+
/* The width of the region.
|
516
|
+
* @return [Integer] the width of the region
|
517
|
+
*/
|
518
|
+
static VALUE region_size(VALUE self)
|
519
|
+
{
|
520
|
+
region_t * r = value_as_region(self);
|
521
|
+
return INT2FIX(r->len);
|
522
|
+
}
|
523
|
+
|
524
|
+
/* Read data from the region.
|
525
|
+
* @return [String] the data read
|
526
|
+
*/
|
527
|
+
static VALUE region_read(VALUE self)
|
528
|
+
{
|
529
|
+
region_t * r = value_as_region(self);
|
530
|
+
return rb_str_new((const char *)r->data, r->len);
|
531
|
+
}
|
532
|
+
|
533
|
+
/* Write data to the region.
|
534
|
+
* @param str [String] the data to write
|
535
|
+
* @return [nil]
|
536
|
+
*/
|
537
|
+
static VALUE region_write(VALUE self, VALUE str)
|
538
|
+
{
|
539
|
+
if (!RB_TYPE_P(str, T_STRING)) {
|
540
|
+
str = rb_funcall(str, rb_intern("to_s"), 0);
|
541
|
+
if (!RB_TYPE_P(str, T_STRING)) {
|
542
|
+
rb_raise(rb_eArgError, "str.to_s is not a string");
|
543
|
+
}
|
544
|
+
}
|
545
|
+
|
546
|
+
region_t * r = value_as_region(self);
|
547
|
+
size_t len = RSTRING_LEN(str);
|
548
|
+
if (len > r->len) {
|
549
|
+
rb_raise(rb_eRangeError, "string is longer than region");
|
550
|
+
}
|
551
|
+
|
552
|
+
memcpy(r->data, StringValuePtr(str), len);
|
553
|
+
return Qnil;
|
554
|
+
}
|
555
|
+
|
556
|
+
#define set_region(var, alignment, region) \
|
557
|
+
do { \
|
558
|
+
region_t * r = value_as_region(region); \
|
559
|
+
if (ralign(r, alignment) != 0) { \
|
560
|
+
rb_raise(rb_eRangeError, "region must be aligned to a %d-byte boundary", alignment); \
|
561
|
+
} \
|
562
|
+
if (sizeof(typeof(*var->shared)) > r->len) { \
|
563
|
+
rb_raise(rb_eRangeError, "region too small: expected >=%lu, got %lu", sizeof(typeof(*var->shared)), r->len); \
|
564
|
+
} \
|
565
|
+
var->region = region; \
|
566
|
+
var->shared = (typeof(var->shared))r->data; \
|
567
|
+
} while(0);
|
568
|
+
|
569
|
+
/*
|
570
|
+
* Document-class: ConcurrentSHM::Mutex
|
571
|
+
* A POSIX-threads mutex, with the `pshared` attribute set to
|
572
|
+
* `PTHREAD_PROCESS_SHARED`, allocated in a shared memory space.
|
573
|
+
*/
|
574
|
+
|
575
|
+
/* Initializes a shared mutex in the specified memory region.
|
576
|
+
* @param region [Region] the memory region
|
577
|
+
* @raise [RangeError] if the region is too small or not aligned to a 16-byte boundary
|
578
|
+
*/
|
579
|
+
static VALUE mutex_initialize(VALUE self, VALUE region)
|
580
|
+
{
|
581
|
+
mutex_t * mu = value_as_mutex(self);
|
582
|
+
set_region(mu, 16, region);
|
583
|
+
__set_finalizer(self, mu);
|
584
|
+
|
585
|
+
if (__shared_retain(&mu->shared->refcount) == 1) {
|
586
|
+
chk_err(pthread_mutexattr_init, (&mu->shared->attr), "");
|
587
|
+
chk_err(pthread_mutexattr_setpshared, (&mu->shared->attr, PTHREAD_PROCESS_SHARED), "");
|
588
|
+
chk_err(pthread_mutex_init, (&mu->shared->mu, &mu->shared->attr), "");
|
589
|
+
}
|
590
|
+
return self;
|
591
|
+
}
|
592
|
+
|
593
|
+
/* Attempts to lock the mutex.
|
594
|
+
* @return [Boolean] `true` if the lock was acquired
|
595
|
+
* @raise [Errno::EAGAIN] if the mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded
|
596
|
+
*/
|
597
|
+
static VALUE mutex_try_lock(VALUE self)
|
598
|
+
{
|
599
|
+
mutex_t * mu = value_as_mutex(self);
|
600
|
+
int err = pthread_mutex_trylock(&mu->shared->mu);
|
601
|
+
switch (err) {
|
602
|
+
case 0:
|
603
|
+
return Qtrue;
|
604
|
+
case EBUSY:
|
605
|
+
return Qfalse;
|
606
|
+
default:
|
607
|
+
rb_syserr_fail_strf(err, "mutex_try_lock");
|
608
|
+
}
|
609
|
+
}
|
610
|
+
|
611
|
+
/* Locks the mutex, blocking until the mutex becomes available, if necessary.
|
612
|
+
* @return [nil]
|
613
|
+
* @raise [Errno::EDEADLK] if the current thread already owns the mutex
|
614
|
+
* @raise [Errno::EAGAIN] if the mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded
|
615
|
+
*/
|
616
|
+
static VALUE mutex_lock(VALUE self)
|
617
|
+
{
|
618
|
+
if (mutex_try_lock(self) == Qtrue) {
|
619
|
+
return Qnil;
|
620
|
+
}
|
621
|
+
|
622
|
+
mutex_t * mu = value_as_mutex(self);
|
623
|
+
int err = (int)(uintptr_t)rb_thread_call_without_gvl((void * (*)(void *))pthread_mutex_lock, &mu->shared->mu, NULL, NULL);
|
624
|
+
|
625
|
+
rb_check_syserr_fail_strf(err, err, "pthread_mutex_lock()");
|
626
|
+
return Qnil;
|
627
|
+
}
|
628
|
+
|
629
|
+
/* Unlocks the mutex.
|
630
|
+
* @raise [Errno::EPERM] if the current thread does not own the mutex
|
631
|
+
* @raise [Errno::EAGAIN] if the mutex could not be acquired because the maximum number of recursive locks for mutex has been exceeded
|
632
|
+
*/
|
633
|
+
static VALUE mutex_unlock(VALUE self)
|
634
|
+
{
|
635
|
+
mutex_t * mu = value_as_mutex(self);
|
636
|
+
chk_err(pthread_mutex_unlock, (&mu->shared->mu), "");
|
637
|
+
return Qnil;
|
638
|
+
}
|
639
|
+
|
640
|
+
/*
|
641
|
+
* Document-class: ConcurrentSHM::Condition
|
642
|
+
* A POSIX-threads condition variable, with the `pshared` attribute set to
|
643
|
+
* `PTHREAD_PROCESS_SHARED`, allocated in a shared memory space.
|
644
|
+
*/
|
645
|
+
|
646
|
+
/* Initializes a shared condition variable in the specified memory region.
|
647
|
+
* @param region [Region] the memory region
|
648
|
+
* @raise [RangeError] if the region is too small or not aligned to a 16-byte boundary
|
649
|
+
*/
|
650
|
+
static VALUE condition_initialize(VALUE self, VALUE region)
|
651
|
+
{
|
652
|
+
condition_t * cond = value_as_condition(self);
|
653
|
+
set_region(cond, 16, region);
|
654
|
+
__set_finalizer(self, cond);
|
655
|
+
|
656
|
+
if (__shared_retain(&cond->shared->refcount) == 1) {
|
657
|
+
chk_err(pthread_condattr_init, (&cond->shared->attr), "");
|
658
|
+
chk_err(pthread_condattr_setpshared, (&cond->shared->attr, PTHREAD_PROCESS_SHARED), "");
|
659
|
+
chk_err(pthread_cond_init, (&cond->shared->cond, &cond->shared->attr), "");
|
660
|
+
}
|
661
|
+
return self;
|
662
|
+
}
|
663
|
+
|
664
|
+
/* Wakes at least one thread waiting on this condition.
|
665
|
+
*/
|
666
|
+
static VALUE condition_signal(VALUE self)
|
667
|
+
{
|
668
|
+
condition_t * cond = value_as_condition(self);
|
669
|
+
chk_err(pthread_cond_signal, (&cond->shared->cond), "");
|
670
|
+
return Qnil;
|
671
|
+
}
|
672
|
+
|
673
|
+
/* Wakes all threads waiting on this condition.
|
674
|
+
*/
|
675
|
+
static VALUE condition_broadcast(VALUE self)
|
676
|
+
{
|
677
|
+
condition_t * cond = value_as_condition(self);
|
678
|
+
chk_err(pthread_cond_broadcast, (&cond->shared->cond), "");
|
679
|
+
return Qnil;
|
680
|
+
}
|
681
|
+
|
682
|
+
struct cond_wait_args {
|
683
|
+
pthread_cond_t * cond;
|
684
|
+
pthread_mutex_t * mu;
|
685
|
+
struct timespec * tv;
|
686
|
+
};
|
687
|
+
|
688
|
+
static void cond_wait_cancel(struct cond_wait_args * args) {
|
689
|
+
chk_err(pthread_cond_broadcast, (args->cond), "");
|
690
|
+
}
|
691
|
+
|
692
|
+
static int cond_wait_without_gvl(struct cond_wait_args * args) {
|
693
|
+
if (args->tv) {
|
694
|
+
return pthread_cond_timedwait(args->cond, args->mu, args->tv);
|
695
|
+
} else {
|
696
|
+
return pthread_cond_wait(args->cond, args->mu);
|
697
|
+
}
|
698
|
+
}
|
699
|
+
|
700
|
+
/* @overload wait(mutex, timeout = nil)
|
701
|
+
* Releases the mutex lock and waits, reacquiring the mutex lock on wakeup.
|
702
|
+
* Returns after the specified timeout passes, if a timeout is specified.
|
703
|
+
* @param mutex [Mutex] the mutex
|
704
|
+
* @param timeout [Numeric] the timeout
|
705
|
+
* @return [Boolean] `false` if the wait timed out, `true` otherwise
|
706
|
+
*/
|
707
|
+
static VALUE condition_wait(int argc, VALUE * argv, VALUE self)
|
708
|
+
{
|
709
|
+
VALUE mutex, timeout;
|
710
|
+
rb_scan_args(argc, argv, "11", &mutex, &timeout);
|
711
|
+
|
712
|
+
condition_t * cond = value_as_condition(self);
|
713
|
+
mutex_t * mu = value_as_mutex(mutex);
|
714
|
+
|
715
|
+
struct cond_wait_args args = { .cond = &cond->shared->cond, .mu = &mu->shared->mu };
|
716
|
+
if (!NIL_P(timeout)) {
|
717
|
+
struct timespec tv = {0};
|
718
|
+
if (RB_TYPE_P(timeout, T_FIXNUM)) {
|
719
|
+
tv.tv_sec = FIX2ULONG(timeout);
|
720
|
+
} else if (RB_TYPE_P(timeout, T_BIGNUM)) {
|
721
|
+
tv.tv_sec = rb_big2ull(timeout);
|
722
|
+
} else if (RB_TYPE_P(timeout, T_FLOAT)) {
|
723
|
+
double v = RFLOAT_VALUE(timeout) + 0.5e-9; // round up to nearest ns
|
724
|
+
tv.tv_sec = (time_t)v;
|
725
|
+
tv.tv_nsec = (v - tv.tv_sec) * 1000000000L;
|
726
|
+
} else {
|
727
|
+
rb_raise(rb_eArgError, "Invalid timeout");
|
728
|
+
}
|
729
|
+
args.tv = &tv;
|
730
|
+
}
|
731
|
+
|
732
|
+
int err = (int)(uintptr_t)rb_thread_call_without_gvl(
|
733
|
+
(void * (*)(void *))cond_wait_without_gvl, &args,
|
734
|
+
(void (*)(void *))cond_wait_cancel, &args);
|
735
|
+
|
736
|
+
if (err == ETIMEDOUT) {
|
737
|
+
return Qfalse;
|
738
|
+
}
|
739
|
+
|
740
|
+
rb_check_syserr_fail_strf(err, err, "pthread_cond_wait()");
|
741
|
+
return Qtrue;
|
742
|
+
}
|
743
|
+
|
744
|
+
/* Calculate the number of shared memory space bytes required by instances of
|
745
|
+
* the specified class. Recognized classes are {Mutex} and {Condition}.
|
746
|
+
* @param type [Class] the specified class.
|
747
|
+
* @raise [ArgumentError] if `type` is not a class or is an unrecognized class.
|
748
|
+
*/
|
749
|
+
static VALUE size_of(VALUE self, VALUE type)
|
750
|
+
{
|
751
|
+
UNUSED(self);
|
752
|
+
|
753
|
+
if (!RB_TYPE_P(type, T_CLASS)) {
|
754
|
+
rb_raise(rb_eArgError, "Expected a class");
|
755
|
+
}
|
756
|
+
|
757
|
+
size_t s;
|
758
|
+
if (type == Mutex) {
|
759
|
+
s = sizeof(struct mutex_shared);
|
760
|
+
} else if (type == Condition) {
|
761
|
+
s = sizeof(struct condition_shared);
|
762
|
+
} else {
|
763
|
+
rb_raise(rb_eArgError, "Unrecognized type");
|
764
|
+
}
|
765
|
+
|
766
|
+
size_t o = s % 16;
|
767
|
+
if (o) {
|
768
|
+
s += 16-o;
|
769
|
+
}
|
770
|
+
return INT2FIX(s);
|
771
|
+
}
|
772
|
+
|
773
|
+
void Init_posix(VALUE ConcurrentSHM)
|
774
|
+
{
|
775
|
+
rb_define_module_function(ConcurrentSHM, "size_of", size_of, 1);
|
776
|
+
|
777
|
+
Finalizer = rb_define_class_under(ConcurrentSHM, "Finalizer", rb_cObject);
|
778
|
+
rb_define_method(Finalizer, "call", __finalize, 1);
|
779
|
+
|
780
|
+
SharedMemory = rb_define_class_under(ConcurrentSHM, "SharedMemory", rb_cIO);
|
781
|
+
rb_define_module_function(SharedMemory, "open", shared_memory_open, -1);
|
782
|
+
rb_define_module_function(SharedMemory, "delete", shared_memory_delete, 1);
|
783
|
+
rb_define_method(SharedMemory, "initialize", shared_memory_initialize, 2);
|
784
|
+
rb_define_method(SharedMemory, "size", shared_memory_size, 0);
|
785
|
+
rb_define_method(SharedMemory, "size=", shared_memory_size_eq, 1);
|
786
|
+
|
787
|
+
Region = rb_define_class_under(ConcurrentSHM, "Region", rb_cObject);
|
788
|
+
rb_define_module_function(Region, "map", region_map, 3);
|
789
|
+
rb_define_module_function(Region, "unmap", region_unmap, 1);
|
790
|
+
rb_define_method(Region, "from", region_from, 0);
|
791
|
+
rb_define_method(Region, "size", region_size, 0);
|
792
|
+
rb_define_method(Region, "[]", region_at, -1);
|
793
|
+
rb_define_method(Region, "alignment", region_alignment, 1);
|
794
|
+
rb_define_method(Region, "aligned?", region_aligned_q, 1);
|
795
|
+
rb_define_method(Region, "read", region_read, 0);
|
796
|
+
rb_define_method(Region, "write", region_write, 1);
|
797
|
+
rb_define_method(Region, "as_intptr", region_as_intptr, 0);
|
798
|
+
rb_define_method(Region, "as_uintptr", region_as_uintptr, 0);
|
799
|
+
|
800
|
+
Mutex = rb_define_class_under(ConcurrentSHM, "Mutex", rb_cObject);
|
801
|
+
rb_define_alloc_func(Mutex, __mutex_alloc);
|
802
|
+
rb_define_method(Mutex, "initialize", mutex_initialize, 1);
|
803
|
+
rb_define_method(Mutex, "lock", mutex_lock, 0);
|
804
|
+
rb_define_method(Mutex, "try_lock", mutex_try_lock, 0);
|
805
|
+
rb_define_method(Mutex, "unlock", mutex_unlock, 0);
|
806
|
+
|
807
|
+
Condition = rb_define_class_under(ConcurrentSHM, "Condition", rb_cObject);
|
808
|
+
rb_define_alloc_func(Condition, __condition_alloc);
|
809
|
+
rb_define_method(Condition, "initialize", condition_initialize, 1);
|
810
|
+
rb_define_method(Condition, "signal", condition_signal, 0);
|
811
|
+
rb_define_method(Condition, "broadcast", condition_broadcast, 0);
|
812
|
+
rb_define_method(Condition, "wait", condition_wait, -1);
|
813
|
+
}
|