1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "config.h"
6#include "bindings/core/v8/ScriptStreamerThread.h"
7
8#include "bindings/core/v8/ScriptStreamer.h"
9#include "platform/Task.h"
10#include "platform/TraceEvent.h"
11#include "public/platform/Platform.h"
12#include "wtf/MainThread.h"
13#include "wtf/PassOwnPtr.h"
14
15namespace blink {
16
17static ScriptStreamerThread* s_sharedThread = 0;
18
19void ScriptStreamerThread::init()
20{
21    ASSERT(!s_sharedThread);
22    ASSERT(isMainThread());
23    s_sharedThread = new ScriptStreamerThread();
24}
25
26void ScriptStreamerThread::shutdown()
27{
28    ASSERT(s_sharedThread);
29    delete s_sharedThread;
30    s_sharedThread = 0;
31}
32
33ScriptStreamerThread* ScriptStreamerThread::shared()
34{
35    return s_sharedThread;
36}
37
38void ScriptStreamerThread::postTask(WebThread::Task* task)
39{
40    ASSERT(isMainThread());
41    MutexLocker locker(m_mutex);
42    ASSERT(!m_runningTask);
43    m_runningTask = true;
44    platformThread().postTask(task);
45}
46
47void ScriptStreamerThread::taskDone()
48{
49    MutexLocker locker(m_mutex);
50    ASSERT(m_runningTask);
51    m_runningTask = false;
52}
53
54blink::WebThread& ScriptStreamerThread::platformThread()
55{
56    if (!isRunning())
57        m_thread = adoptPtr(blink::Platform::current()->createThread("ScriptStreamerThread"));
58    return *m_thread;
59}
60
61ScriptStreamingTask::ScriptStreamingTask(v8::ScriptCompiler::ScriptStreamingTask* task, ScriptStreamer* streamer)
62    : m_v8Task(adoptPtr(task)), m_streamer(streamer) { }
63
64void ScriptStreamingTask::run()
65{
66    TRACE_EVENT0("v8", "v8.parseOnBackground");
67    // Running the task can and will block: SourceStream::GetSomeData will get
68    // called and it will block and wait for data from the network.
69    m_v8Task->Run();
70    // Post a task to the main thread to signal that V8 has completed the
71    // streaming.
72    callOnMainThread(WTF::bind(&ScriptStreamer::streamingComplete, m_streamer));
73    ScriptStreamerThread::shared()->taskDone();
74}
75
76} // namespace blink
77