{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## 5-9-3 スレッド固有のデータ" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"in progress\"\n" ] }, { "data": { "text/plain": [ "\"in progress\"" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "thread = Thread.fork {\n", " Thread.current[:status] = 'in progress'\n", " sleep 0.5\n", "}\n", "\n", "sleep 0.1\n", "\n", "# シンボルと文字列どちらでも同じ値が取得できる.\n", "p thread[:status]\n", "thread['status']" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5-9-4 ライフサイクル" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"sleep\"\n", "true\n" ] }, { "data": { "text/plain": [ "true" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = Thread.fork { sleep 1 }\n", "\n", "sleep 0.1\n", "\n", "p t.status\n", "p t.alive?\n", "t.stop?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5-9-5 スレッドの操作" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"sleep\"\n", "hi\n" ] }, { "data": { "text/plain": [ "#" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t = Thread.fork {\n", " Thread.stop\n", " puts 'hi'\n", "}\n", "\n", "sleep 0.1\n", "\n", "p t.status\n", "t.run" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5-9-6 例外の扱い" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = Thread.fork { raise }\n", "# 元のスレッドで例外が発生する.\n", "t.join" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Thread#join 等を呼ばない場合は元スレッドで例外は上らない\n", "t = Thread.fork { raise }" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "t = Thread.fork {\n", " begin\n", " loop { }\n", " ensure\n", " puts 'ensureing...'\n", " end\n", "}\n", "\n", "t.raise\n", "\n", "begin\n", " t.join\n", "rescue\n", " p t.status\n", "end" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Ruby 2.5.1", "language": "ruby", "name": "ruby" }, "language_info": { "file_extension": ".rb", "mimetype": "application/x-ruby", "name": "ruby", "version": "2.5.1" } }, "nbformat": 4, "nbformat_minor": 2 }