Module: PThread

Extended by:
FFI::Library, Helper
Included in:
Mutex, MutexAttr
Defined in:
lib/scratch.rb

Defined Under Namespace

Modules: Helper Classes: Int, Mutex, MutexAttr

Constant Summary

Constants included from Helper

Helper::MAP_FAILED, Helper::MAP_PRIVATE, Helper::MAP_SHARED, Helper::O_CREAT, Helper::O_RDWR, Helper::PROT_EXEC, Helper::PROT_NONE, Helper::PROT_READ, Helper::PROT_WRITE, Helper::PTHREAD_PROCESS_SHARED

Class Method Summary collapse

Class Method Details

.call(err_msg = 'error in pthreads', &block) ⇒ Object

Raises:

  • (SystemCallError)


122
123
124
125
# File 'lib/scratch.rb', line 122

def call(err_msg = 'error in pthreads', &block)
  ret = yield
  raise SystemCallError.new(err_msg, ret) unless ret == 0
end

.testObject



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
# File 'lib/scratch.rb', line 248

def test
  puts "hi #{Helper.sizeof_pthread_mutex_t}"
  puts Mutex.new


  fd = LibC.call { RT.shm_open("/foo", O_CREAT | O_RDWR, 0777) }
  LibC.call { LibC.ftruncate(fd, 100) }
  pointer = LibC.mmap(nil, 100, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
  puts pointer
  puts pointer == MAP_FAILED
  puts MAP_FAILED

  attr = MutexAttr.new
  attr.pshared = PTHREAD_PROCESS_SHARED

  mutex = Mutex.new(pointer, attr.pointer)


  fd = LibC.call { RT.shm_open("/someint", O_CREAT | O_RDWR, 0777) }
  LibC.call { LibC.ftruncate(fd, 100) }
  pointer = LibC.mmap(nil, 100, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)
  abort "failed" if pointer == MAP_FAILED

  value = Int.new(pointer)
  value[:val] = 0
  puts "int[0]: #{value[:val]}"

  puts "parent has mutex #{mutex}"

  n = 10000

  child = fork do
    puts "child and I have mutex: #{mutex}"

    n.times do |i|
      mutex.lock
      value[:val] = (value[:val] + 1)
      mutex.unlock
    end
  end

  n.times do |i|
    mutex.lock
    value[:val] = (value[:val] + 1)
    mutex.unlock
  end

  Process.wait(child)

  puts "value is now #{value[:val]}"
end