Skip to content

Commit 149ddf5

Browse files
authored
Merge pull request #6 from YiwenAI/main
add ray core tasks
2 parents a94c06d + 4fa720b commit 149ddf5

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import ray
2+
import time
3+
4+
5+
# A regular Python function.
6+
def normal_function():
7+
return 1
8+
9+
10+
# By adding the `@ray.remote` decorator, a regular Python function
11+
# becomes a Ray remote function.
12+
@ray.remote
13+
def my_function():
14+
return 1
15+
16+
17+
# To invoke this remote function, use the `remote` method.
18+
# This will immediately return an object ref (a future) and then create
19+
# a task that will be executed on a worker process.
20+
obj_ref = my_function.remote()
21+
22+
# The result can be retrieved with ``ray.get``.
23+
assert ray.get(obj_ref) == 1
24+
25+
26+
@ray.remote
27+
def slow_function():
28+
time.sleep(10)
29+
return 1
30+
31+
32+
# Ray tasks are executed in parallel.
33+
# All computation is performed in the background, driven by Ray's internal event loop.
34+
for _ in range(4):
35+
# This doesn't block.
36+
slow_function.remote()
37+
38+
39+
# Specify required resources.
40+
@ray.remote(num_cpus=4, num_gpus=2)
41+
def my_function():
42+
return 1
43+
44+
45+
# Override the default resource requirements.
46+
my_function.options(num_cpus=3).remote()
47+
48+
49+
@ray.remote
50+
def function_with_an_argument(value):
51+
return value + 1
52+
53+
54+
obj_ref1 = my_function.remote()
55+
assert ray.get(obj_ref1) == 1
56+
57+
# You can pass an object ref as an argument to another Ray task.
58+
obj_ref2 = function_with_an_argument.remote(obj_ref1)
59+
assert ray.get(obj_ref2) == 2
60+
61+
62+
object_refs = [slow_function.remote() for _ in range(2)]
63+
# Return as soon as one of the tasks finished execution.
64+
ready_refs, remaining_refs = ray.wait(object_refs, num_returns=1, timeout=None)

0 commit comments

Comments
 (0)