我有以下代码:
(defn compile-report [id]
(let [a (gen-first-part id)
b (gen-second-part id)
c (gen-third-part id)
d (gen-fourth-part id)]
(conj a b c d)))
每个&x-gen-x-part'函数是cpu密集型的。据我了解,let表单将在单个线程上串行运行这些计算。如果我有一个核心机器,那么在它自己的线程上运行它们就没有意义,因为它们都是cpu绑定的。但是,我有一台4芯机器。如何利用每个核心并将这些功能分配到自己的核心?感谢。
答案 0 :(得分:10)
您可以将CPU密集型功能包装到future
s:
buttonVoice.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
// Get activity from either SearchableInfo or ComponentName
ComponentName searchActivity = mComponentName;
// Wrap component in intent
Intent queryIntent = new Intent(Intent.ACTION_SEARCH);
queryIntent.setComponent(searchActivity);
// Wrap query intent in pending intent
PendingIntent pending = PendingIntent.getActivity(getContext(), 0, queryIntent, PendingIntent.FLAG_ONE_SHOT);
// Create bundle now because if we wrap it in pending intent, it becomes immutable
Bundle queryExtras = new Bundle();
// Create voice intent
Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZER_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak");
voiceIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, searchActivity
voiceIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Wrap the pending intent & bundle inside the voice intent
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT, pending);
voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT_BUNDLE, queryExtras);
// Start the voice search
getContext().startActivity(voiceIntent);
}
}
它将使它们在不同的线程中运行。 (defn compile-report [id]
(let [a (future (gen-first-part id))
b (future (gen-second-part id))
c (future (gen-third-part id))
d (future (gen-fourth-part id))]
(conj @a @b @c @d)))
表示@a
将阻止,直到结果可用。
如果您的函数处理更大的Clojure数据集,您也可以查看pmap
。