# 是否能在串行的循环中执行并行的循环？

``````@ti.kernel
def prefix_sum_interal(t:ti.u32,h:ti.u32,x:ti.template(),y:ti.template()):
for i in range(h):
src = ((i>>t)<<(t+1)) + (1<<t) - 1
dst = src + 1 + (i & ((1<<t) - 1))
y[dst] += y[src]

def prefix_sum(x:ti.template(),y:ti.template()):
n = x.shape[0]
y.copy_from(x)
h = n // 2
total_step = q_log2(n)
for t in range(total_step):
prefix_sum_interal(t,h,x,y)
``````

``````@ti.kernel
def prefix_sum(x:ti.template(),y:ti.template()):
n = x.shape[0]
h = n // 2
total_step = q_log2(n)
for i in range(x):
y[i] = x[i]
ti.loop_config(serialize=True)
for t in range(total_step):
ti.loop_config(serialize=False)
prefix_sum_interal(t,h,x,y)
``````

``````@ti.kernel
def prefix_sum(x:ti.template(),y:ti.template()):
n = x.shape[0]
h = n // 2
total_step = q_log2(n)
for i in range(x):
y[i] = x[i]
for i in range(h):
for t in range(total_step):
src = ((i>>t)<<(t+1)) + (1<<t) - 1
dst = src + 1 + (i & ((1<<t) - 1))
y[dst] += y[src]
``````
1 Like

@StellarWarp 如果想在串行的循环中执行并行循环，目前最简单的办法确实是把串行写在python，然后把并行放进taichi kernel， 如果需要复用代码的话可以放进ti.func.